Skip to content

Content Server (OTCS)

OTCS Module to implement functions to read / write Content Server objects such as Users, Groups, Nodes, Workspaces, ...

Class: OTCS Methods:

init : class initializer config : returns config data set cookie : returns cookie information credentials: Get credentials (username and password) set_credentials: Set new credentials hostname: Get the configured OTCS hostname set_hostname: Set the hostname of OTCS base_url : Get OTCS base URL cs_url: Get the Extended ECM (OTCS) URL rest_url : Get OTCS REST base URL

request_form_header: Deliver the request header used for the CRUD REST API calls. request_json_header: Deliver the request header for REST calls that require content type application/json. request_download_header: Deliver the request header used for download REST API calls. These calls accept application/octet-stream.

Converts the text property of a request response object

to a Python dict in a safe way

lookup_result_value: Lookup a property value based on a provided key / value pair in the response properties of an Extended ECM REST API call exist_result_item: Check existence of key / value pair in the response properties of an Extended ECM REST API call. get_result_value: Read an item value from the REST API response. This is considering the most typical structures delivered by V2 REST API of Extended ECM

is_configured: returns true if the OTCS pod is ready to serve requests authenticate : Authenticates at Content Server and retrieve OTCS Ticket.

get_server_info: return OTCS server information

apply_config: Apply Content Server administration settings from XML file

get_user: Lookup Content Server user add_user: Add Content Server user search_user: Find a user based on search criteria update_user: Update a defined field for a user get_user_profile: Get the profile (settings) for the current user update_user_profile: Update a defined field of the user profile (settings) for the current user. update_user_photo: Update a user with a profile photo (which must be an existing node) is_proxy: Check if a user (login name) is a proxy of the current user get_user_proxies: Get the list of proxy users for the current user add_user_proxy: Add a proxy to the current (authenticated) user add_favorite: Add a favorite for the current (authenticated) user add_favorite_tab: Add a favorite tab for the current (authenticated) user

get_group: Lookup Content Server group add_group: Add Content Server group get_group_members: Get Content Server group members add_group_member: Add a user or group to a target group

get_node: Get a node based on the node ID get_node_by_parent_and_name: Get a node based on the parent ID and name get_node_by_workspace_and_path: Get a node based on the workspace ID and path (list of folder names) get_node_by_volume_and_path: Get a node based on the volume ID and path get_node_from_nickname: Get a node based on the nickname set_node_nickname: Assign a nickname to an Extended ECM node (e.g. workspace) get_subnodes: get children nodes of a parent node get_node_actions: get possible actions for a node rename_node: Change the name and description of a node get_volumes: Get all Volumes get_volume: Get Volume information based on the volume type ID check_node_name: Check if a a node name in a parent location has a name collision upload_file_to_volume: Fetch a file from a URL or local filesystem and upload it to a Extended ECM volume upload_file_to_parent: Upload a document to a parent folder add_document_version: Add a version to an Extended ECM document get_latest_document_version: Get latest version of a document node based on the node ID. get_document_content: get content of a document version download_document: Download a document download_config_file: Download a config file from a given OTCS URL. This is NOT for downloading documents from within the OTCS repository

search: search for a search term using Extended ECM search engine

get_external_system_connection: Get Extended ECM external system connection add_external_system_connection: Add Extended ECM external system connection

create_transport_workbench: Create a Workbench in the Transport Volume unpack_transport_package: Unpack an existing Transport Package into an existing Workbench deploy_workbench: Deploy an existing Workbench deploy_transport: Main method to deploy a transport. This uses subfunctions to upload, unpackage and deploy the transport, and creates the required workbench replace_transport_placeholders: Search and replace strings in the XML files of the transport packlage

get_business_object_types: Get information for all configured business object types get_business_object_type: Get information for a specific business object type get_business_objects: Get all business objects for an external system and a given business object type.

get_workspace_types: Get all workspace types configured in Extended ECM get_workspace_create_form: Get the Workspace create form get_workspace: Get a workspace node get_workspace_instances: Get all instances of a given workspace type get_workspace_by_type_and_name: Lookup workspace based on workspace type name and workspace name get_workspace_by_business_object: Lookup workspace based by an business object of an external system create_workspace: Create a new business workspace create_workspace_relationship: Create a relationship between two workspaces get_workspace_relationships: get a list of related workspaces get_workspace_roles: Get the Workspace roles add_member_to_workspace: Add member to workspace role. Check that the user is not yet a member remove_member_from_workspace: Remove member from workspace role assign_workspace_permissions: Update workspace permissions for a given role update_workspace_icon: Update a workspace with a with a new icon (which is uploaded)

get_unique_names: Get information on definition of Unique Names.

create_item: Create an item in Extended ECM (e.g. folder or URL item) update_item: Update an item in Extended ECM (e.g. folder or URL item) get_document_templates: Get all document templates for a given target location create_document_from_template: Create a document based on a document template

get_web_report_parameters: Get parameters of a Web Report run_web_report: Run a Web Report that is identified by its nick name

install_cs_application: Install a CS Application (based on WebReports)

assign_item_to_user_group: Assign an item (e.g. Workspace or document) to a list of users or groups

convert_permission_string_to_permission_value: Convert a list of permission names to a permission value convert_permission_value_to_permission_string: Convert a permission value to a list of permission strings assign_permission: Assign permissions to an item for a defined user or group

get_node_categories: Get categories assigned to a node get_node_category: Get a specific category assigned to a node get_node_category_ids: Get list of all category definition IDs that are assign to the node. get_node_category_definition: Get category definition (category id and attribute IDs and types) assign_category: Assign a category to a node set_category_value: Set a value for a specific category attribute to a node

assign_classification: Assign a classification to an item assign_rm_classification: Assign a Records management classification to an item

register_workspace_template: Register a workspace template for Extended ECM for Engineering

get_records_management_rsis: Get the ist of RSIs together with their RSI schedules get_records_management_codes: Get Records Management Codes update_records_management_codes: Update the Records Management Codes create_records_management_rsi: Create a new Records Management RSI item create_records_management_rsi_schedule: Create a schedule for an existing RSI item create_records_management_hold: Create a Records Management Hold get_records_management_holds: Get a list of all Records Management Holds in the system. import_records_management_codes: Import RM codes from a config file import_records_management_rsis: Import RM RSIs from a config file import_records_management_settings: Import Records Management settings from a config file import_physical_objects_codes: Import Physical Objects codes from a config file import_physical_objects_settings: Import Physical Objects settings from a config file import_physical_objects_locators: Import Physical Objects locators from a config file import_security_clearance_codes: Import Securioty Clearance codes from a config file

assign_user_security_clearance: Assign a Security Clearance level to a user assign_user_supplemental_markings: Assign a list of Supplemental Markings to a user

check_workspace_aviator: Check if Content Aviator is enabled for a workspace update_workspace_aviator: Enable or disable the Content Aviator for a workspace

OTCS

Used to automate stettings in OpenText Extended ECM.

Source code in pyxecm/otcs.py
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
class OTCS:
    """Used to automate stettings in OpenText Extended ECM."""

    _config: dict
    _cookie = None
    _otcs_ticket = None
    _otds_ticket = None

    def __init__(
        self,
        protocol: str,
        hostname: str,
        port: int,
        public_url: str,
        username: str | None = None,
        password: str | None = None,
        user_partition: str = "Content Server Members",
        resource_name: str = "cs",
        default_license: str = "X3",
        otds_ticket: str | None = None,
        base_path: str = "/cs/cs",
    ):
        """Initialize the OTCS object

        Args:
            protocol (str): Either http or https.
            hostname (str): The hostname of Extended ECM server to communicate with.
            port (int): The port number used to talk to the Extended ECM server.
            public_url (str): public (external) URL
            username (str, optional): The admin user name of Extended ECM. Optional if otds_ticket is provided.
            password (str, optional): The admin password of Extended ECM. Optional if otds_ticket is provided.
            user_partition (str): Name of the OTDS partition for OTCS users. Default is "Content Server Members".
            resource_name (str, optional): Name of the OTDS resource for OTCS. Dault is "cs".
            default_license (str, optional): name of the default user license. Default is "X3".
            otds_ticket (str, optional): Authentication ticket of OTDS
        """

        # Initialize otcs_config as an empty dictionary
        otcs_config = {}

        if hostname:
            otcs_config["hostname"] = hostname
        else:
            otcs_config["hostname"] = "otcs-admin-0"

        if protocol:
            otcs_config["protocol"] = protocol
        else:
            otcs_config["protocol"] = "http"

        if port:
            otcs_config["port"] = port
        else:
            otcs_config["port"] = 8080

        otcs_config["publicUrl"] = public_url

        if username:
            otcs_config["username"] = username
        else:
            otcs_config["username"] = "admin"

        if password:
            otcs_config["password"] = password
        else:
            otcs_config["password"] = ""

        if user_partition:
            otcs_config["partition"] = user_partition
        else:
            otcs_config["partition"] = ""

        if resource_name:
            otcs_config["resource"] = resource_name
        else:
            otcs_config["resource"] = ""

        if default_license:
            otcs_config["license"] = default_license
        else:
            otcs_config["license"] = ""

        otcs_base_url = protocol + "://" + otcs_config["hostname"]
        if str(port) not in ["80", "443"]:
            otcs_base_url += ":{}".format(port)
        otcs_config["baseUrl"] = otcs_base_url
        otcs_support_url = otcs_base_url + "/cssupport"
        otcs_config["supportUrl"] = otcs_support_url
        otcs_public_support_url = public_url + "/cssupport"
        otcs_config["supportPublicUrl"] = otcs_public_support_url

        otcs_config["configuredUrl"] = otcs_support_url + "/csconfigured"

        otcs_url = otcs_base_url + base_path
        otcs_config["csUrl"] = otcs_url
        otcs_public_url = public_url + base_path
        otcs_config["csPublicUrl"] = otcs_public_url

        otcs_rest_url = otcs_url + "/api"
        otcs_config["restUrl"] = otcs_rest_url

        otcs_config["isReady"] = otcs_rest_url + "/v1/ping"
        otcs_config["authenticationUrl"] = otcs_rest_url + "/v1/auth"
        otcs_config["serverInfoUrl"] = otcs_rest_url + "/v1/serverinfo"
        otcs_config["membersUrl"] = otcs_rest_url + "/v1/members"
        otcs_config["membersUrlv2"] = otcs_rest_url + "/v2/members"
        otcs_config["nodesUrl"] = otcs_rest_url + "/v1/nodes"
        otcs_config["nodesUrlv2"] = otcs_rest_url + "/v2/nodes"
        otcs_config["doctemplatesUrl"] = otcs_rest_url + "/v2/doctemplates"
        otcs_config["nicknameUrl"] = otcs_rest_url + "/v2/nicknames"
        otcs_config["importSettingsUrl"] = otcs_rest_url + "/v2/import/settings/admin"
        otcs_config["searchUrl"] = otcs_rest_url + "/v2/search"
        otcs_config["volumeUrl"] = otcs_rest_url + "/v2/volumes"
        otcs_config["externalSystemUrl"] = otcs_rest_url + "/v2/externalsystems"
        otcs_config["businessObjectsUrl"] = otcs_rest_url + "/v2/businessobjects"
        otcs_config["businessObjectTypesUrl"] = (
            otcs_rest_url + "/v2/businessobjecttypes"
        )
        otcs_config["businessObjectsSearchUrl"] = (
            otcs_rest_url + "/v2/forms/businessobjects/search"
        )
        otcs_config["businessWorkspaceTypesUrl"] = (
            otcs_rest_url + "/v2/businessworkspacetypes"
        )
        otcs_config["businessworkspacecreateform"] = (
            otcs_rest_url + "/v2/forms/businessworkspaces/create"
        )
        otcs_config["businessWorkspacesUrl"] = otcs_rest_url + "/v2/businessworkspaces"
        otcs_config["uniqueNamesUrl"] = otcs_rest_url + "/v2/uniquenames"
        otcs_config["favoritesUrl"] = otcs_rest_url + "/v2/members/favorites"
        otcs_config["webReportsUrl"] = otcs_rest_url + "/v1/webreports"
        otcs_config["csApplicationsUrl"] = otcs_rest_url + "/v2/csapplications"
        otcs_config["xEngProjectTemplateUrl"] = (
            otcs_rest_url + "/v2/xengcrt/projecttemplate"
        )
        otcs_config["rsisUrl"] = otcs_rest_url + "/v2/rsis"
        otcs_config["rsiSchedulesUrl"] = otcs_rest_url + "/v2/rsischedules"
        otcs_config["recordsManagementUrl"] = otcs_rest_url + "/v1/recordsmanagement"
        otcs_config["recordsManagementUrlv2"] = otcs_rest_url + "/v2/recordsmanagement"
        otcs_config["userSecurityUrl"] = otcs_rest_url + "/v2/members/usersecurity"
        otcs_config["physicalObjectsUrl"] = otcs_rest_url + "/v1/physicalobjects"
        otcs_config["securityClearancesUrl"] = otcs_rest_url + "/v1/securityclearances"
        otcs_config["holdsUrl"] = otcs_rest_url + "/v1/holds"
        otcs_config["holdsUrlv2"] = otcs_rest_url + "/v2/holds"
        otcs_config["validationUrl"] = otcs_rest_url + "/v1/validation/nodes/names"
        otcs_config["aiUrl"] = otcs_rest_url + "/v2/ai/nodes"

        self._config = otcs_config
        self._otds_ticket = otds_ticket

    def config(self) -> dict:
        """Returns the configuration dictionary

        Returns:
            dict: Configuration dictionary
        """
        return self._config

    def cookie(self) -> dict:
        """Returns the login cookie of Extended ECM.
           This is set by the authenticate() method

        Returns:
            dict: Estended ECM cookie
        """
        return self._cookie

    def credentials(self) -> dict:
        """Get credentials (username + password)

        Returns:
            dict: dictionary with username and password
        """
        return {
            "username": self.config()["username"],
            "password": self.config()["password"],
        }

    def set_credentials(self, username: str = "admin", password: str = ""):
        """Set the credentials for Extended ECM for the based on user name and password.

        Args:
            username (str, optional): Username. Defaults to "admin".
            password (str, optional): Password of the user. Defaults to "".
        """
        self.config()["username"] = username
        self.config()["password"] = password

    def hostname(self) -> str:
        """Returns the hostname of Extended ECM (e.g. "otcs")

        Returns:
            str: hostname
        """
        return self.config()["hostname"]

    def set_hostname(self, hostname: str):
        """Sets the hostname of Extended ECM

        Args:
            hostname (str): new hostname
        """
        self.config()["hostname"] = hostname

    def base_url(self) -> str:
        """Returns the base URL of Extended ECM

        Returns:
            str: base URL
        """
        return self.config()["baseUrl"]

    def cs_url(self) -> str:
        """Returns the Extended ECM URL

        Returns:
            str: Extended ECM URL
        """
        return self.config()["csUrl"]

    def cs_public_url(self) -> str:
        """Returns the public (external) Extended ECM URL (incl. base_path /cs/cs )

        Returns:
            str: Extended ECM Public URL
        """
        return self.config()["csPublicUrl"]

    def cs_support_url(self) -> str:
        """Returns the Extended ECM Support URL

        Returns:
            str: Extended ECM Support URL
        """
        return self.config()["supportUrl"]

    def cs_support_public_url(self) -> str:
        """Returns the Extended ECM Public Support URL

        Returns:
            str: Extended ECM Public Support URL
        """
        return self.config()["supportPublicUrl"]

    def rest_url(self) -> str:
        """Returns the REST URL of Extended ECM

        Returns:
            str: REST URL
        """
        return self.config()["restUrl"]

    def request_form_header(self) -> dict:
        """Deliver the request header used for the CRUD REST API calls.
           Consists of Cookie + Form Headers (see global variable)

        Args:
            None.
        Return:
            dict: request header values
        """

        # create union of two dicts: cookie and headers
        # (with Python 3.9 this would be easier with the "|" operator)
        request_header = {}
        request_header.update(self.cookie())
        request_header.update(REQUEST_FORM_HEADERS)

        return request_header

    # end method definition

    def request_json_header(self) -> dict:
        """Deliver the request header for REST calls that require content type application/json.
           Consists of Cookie + Json Headers (see global variable)

        Args:
            None.
        Return:
            dict: request header values
        """

        # create union of two dicts: cookie and headers
        # (with Python 3.9 this would be easier with the "|" operator)
        request_header = {}
        request_header.update(self.cookie())
        request_header.update(REQUEST_JSON_HEADERS)

        return request_header

    # end method definition

    def request_download_header(self) -> dict:
        """Deliver the request header used for the CRUD REST API calls.
           Consists of Cookie + Form Headers (see global vasriable)

        Args:
            None.
        Return:
            dict: request header values
        """

        # create union of two dicts: cookie and headers
        # (with Python 3.9 this would be easier with the "|" operator)
        request_header = {}
        request_header.update(self.cookie())
        request_header.update(REQUEST_DOWNLOAD_HEADERS)

        return request_header

    # end method definition

    def parse_request_response(
        self,
        response_object: object,
        additional_error_message: str = "",
        show_error: bool = True,
    ) -> dict | None:
        """Converts the text property of a request response object to a Python dict in a safe way
            that also handles exceptions.

            Content Server may produce corrupt response when it gets restarted
            or hitting resource limits. So we try to avoid a fatal error and bail
            out more gracefully.

        Args:
            response_object (object): this is reponse object delivered by the request call
            additional_error_message (str): print a custom error message
            show_error (bool): if True log an error, if False log a warning

        Returns:
            dict: response or None in case of an error
        """

        if not response_object:
            return None

        try:
            dict_object = json.loads(response_object.text)
        except json.JSONDecodeError as exception:
            if additional_error_message:
                message = "Cannot decode response as JSon. {}; error -> {}".format(
                    additional_error_message, exception
                )
            else:
                message = "Cannot decode response as JSon; error -> {}".format(
                    exception
                )
            if show_error:
                logger.error(message)
            else:
                logger.warning(message)
            return None
        else:
            return dict_object

    # end method definition

    def lookup_result_value(
        self, response: dict, key: str, value: str, return_key: str
    ) -> str | None:
        """Lookup a property value based on a provided key / value pair in the
           response properties of an Extended ECM REST API call.

        Args:
            response (dict): REST response from an OTCS REST Call
            key (str): property name (key)
            value (str): value to find in the item with the matching key
            return_key (str): determines which value to return based on the name of the dict key
        Returns:
            str: value of the property with the key defined in "return_key"
                 or None if the lookup fails
        """

        if not response:
            return None
        if not "results" in response:
            return None

        results = response["results"]
        # check if results is a list or a dict (both is possible -
        # dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value:
            data = results["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data["properties"]
                if (
                    key in properties
                    and properties[key] == value
                    and return_key in properties
                ):
                    return properties[return_key]
                else:
                    return None
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                for item in data:
                    properties = item["properties"]
                    if (
                        key in properties
                        and properties[key] == value
                        and return_key in properties
                    ):
                        return properties[return_key]
                return None
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
        elif isinstance(results, list):
            # result is a list - we need index value
            for result in results:
                data = result["data"]
                if isinstance(data, dict):
                    # data is a dict - we don't need index value:
                    properties = data["properties"]
                    if (
                        key in properties
                        and properties[key] == value
                        and return_key in properties
                    ):
                        return properties[return_key]
                elif isinstance(data, list):
                    # data is a list we iterate through the list and try to find the key:
                    for item in data:
                        properties = item["properties"]
                        if (
                            key in properties
                            and properties[key] == value
                            and return_key in properties
                        ):
                            return properties[return_key]
                else:
                    logger.error(
                        "Data needs to be a list or dict but it is -> %s",
                        str(type(data)),
                    )
                    return None
            return None
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return None

    # end method definition

    def exist_result_item(
        self, response: dict, key: str, value: str, property_name: str = "properties"
    ) -> bool:
        """Check existence of key / value pair in the response properties of an Extended ECM REST API call.

        Args:
            response (dict): REST response from an OTCS REST Call
            key (str): property name (key)
            value (str): value to find in the item with the matching key
            property_name (str, optional): name of the substructure that includes the values
        Returns:
            bool: True if the value was found, False otherwise
        """

        if not response:
            return False
        if not "results" in response:
            return False

        results = response["results"]
        # check if results is a list or a dict (both is possible - dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value:
            if not "data" in results:
                return False
            data = results["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                if property_name and not property_name in data:
                    logger.error(
                        "There's no -> %s dictionary in data -> %s", property_name, data
                    )
                    return False
                properties = data[property_name]
                if isinstance(properties, dict):
                    if key in properties:
                        return properties[key] == value
                    else:
                        return False
                elif isinstance(properties, list):
                    # properties is a list we iterate through the list and try to find the key:
                    for item in properties:
                        if key in item and item[key] == value:
                            return True
                else:
                    logger.error(
                        "Properties needs to be a list or dict but it is -> %s",
                        str(type(properties)),
                    )
                    return False
            elif isinstance(data, list):
                # data is a list
                for item in data:
                    if property_name and not property_name in item:
                        logger.error(
                            "There's no -> %s dictionary in the data list item -> %s",
                            property_name,
                            item,
                        )
                        continue
                    # if properties if passed as empty string then we assume that
                    # the key fields are directly in the item dictionary. This is
                    # the case e.g. with the V2 Proxy APIs
                    if not property_name:
                        properties = item
                    else:
                        properties = item[property_name]
                    if key in properties and properties[key] == value:
                        return True
                return False
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return False
        elif isinstance(results, list):
            # result is a list - we need index value
            for result in results:
                if not "data" in result:
                    continue
                data = result["data"]
                if isinstance(data, dict):
                    # data is a dict - we don't need index value:
                    properties = data[property_name]
                    if key in properties and properties[key] == value:
                        return True
                elif isinstance(data, list):
                    # data is a list we iterate through the list and try to find the key:
                    for item in data:
                        properties = item[property_name]
                        if key in properties and properties[key] == value:
                            return True
                else:
                    logger.error(
                        "Data needs to be a list or dict but it is -> %s",
                        str(type(data)),
                    )
                    return False
            return False
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return False

    # end method definition

    def get_result_value(
        self,
        response: dict,
        key: str,
        index: int = 0,
        property_name: str = "properties",
    ) -> str | None:
        """Read an item value from the REST API response. This is considering
           the most typical structures delivered by V2 REST API of Extended ECM.
           See developer.opentext.com for more details.

        Args:
            response (dict): REST API response object
            key (str): key to find (e.g. "id", "name", ...)
            index (int, optional): In case a list of results is delivered the index
                                   to use (1st element has index  0). Defaults to 0.
            property_name (str, optional): name of the sub dictionary holding the actual values.
                                           Default is "properties".
        Returns:
            str: value of the item with the given key for None if no value is found for the given key.
        """

        # First do some sanity checks:
        if not response:
            logger.info("Empty REST response - returning None")
            return None
        if not "results" in response:
            logger.error("No 'results' key in REST response - returning None")
            return None

        results = response["results"]
        if not results:
            logger.info("No results found!")
            return None

        # check if results is a list or a dict (both is possible - dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value

            # this is a special treatment for the businessworkspaces REST API - it returns
            # for "Create business workspace" the ID directly in the results dict (without data substructure)
            if key in results:
                return results[key]
            data = results["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                properties = data[0][property_name]
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
            logger.debug("Properties of results (dict) -> %s", str(properties))
            # For nearly all OTCS REST Calls perperties is a dict:
            if isinstance(properties, dict):
                if not key in properties:
                    logger.error("Key -> %s is not in result properties!", key)
                    return None
                return properties[key]
            # but there are some strange ones that have other names for
            # properties and may use a list - see e.g. /v2/holds
            elif isinstance(properties, list):
                if index > len(properties) - 1:
                    logger.error(
                        "Illegal Index -> %s given. List has only -> %s elements!",
                        str(index),
                        str(len(properties)),
                    )
                    return None
                return properties[index][key]
            else:
                logger.error(
                    "Properties needs to be a list or dict but it is -> %s",
                    str(type(properties)),
                )
                return False
        elif isinstance(results, list):
            # result is a list - we need a valid index:
            if index > len(results) - 1:
                logger.error(
                    "Illegal Index -> %s given. List has only -> %s elements!",
                    str(index),
                    str(len(results)),
                )
                return None
            data = results[index]["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
            elif isinstance(data, list):
                # data is a list - this has typically just one item, so we use 0 as index
                properties = data[0][property_name]
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s", str(type(data))
                )
                return None
            logger.debug(
                "Properties of results (list, index -> %s) -> %s",
                str(index),
                properties,
            )
            if not key in properties:
                logger.error("Key -> %s is not in result properties!", key)
                return None
            return properties[key]
        else:
            logger.error(
                "Result needs to be a list or dict but it is -> %s", str(type(results))
            )
            return None

    # end method definition

    def is_configured(self) -> bool:
        """Checks if the Content Server pod is configured to receive requests.

        Args:
            None.
        Returns:
            bool: True if pod is ready. False if pod is not yet ready.
        """

        request_url = self.config()["configuredUrl"]

        logger.info("Trying to retrieve OTCS URL -> %s", request_url)

        try:
            response = requests.get(
                url=request_url,
                headers=REQUEST_JSON_HEADERS,
                timeout=REQUEST_TIMEOUT,
            )
        except requests.exceptions.RequestException as exception:
            logger.warning(
                "Unable to connect to -> %s; warning -> %s",
                request_url,
                exception.strerror,
            )
            logger.warning("OTCS service may not be ready yet.")
            return False

        if not response.ok:
            logger.warning(
                "Unable to connect to -> %s; status -> %s; warning -> %s",
                request_url,
                response.status_code,
                response.text,
            )
            return False

        return True

    # end method definition

    def is_ready(self) -> bool:
        """Checks if the Content Server pod is ready to receive requests.

        Args:
            None.
        Returns:
            bool: True if pod is ready. False if pod is not yet ready.
        """

        request_url = self.config()["isReady"]

        logger.info("Trying to retrieve OTCS URL -> %s", request_url)

        try:
            response = requests.get(
                url=request_url,
                headers=REQUEST_JSON_HEADERS,
                timeout=2,
            )
        except requests.exceptions.RequestException as exception:
            logger.warning(
                "Unable to connect to -> %s; warning -> %s",
                request_url,
                exception.strerror,
            )
            logger.warning("OTCS service may not be ready yet.")
            return False

        if not response.status_code == 200:
            logger.warning(
                "Unable to connect to -> %s; status -> %s; warning -> %s",
                request_url,
                response.status_code,
                response.text,
            )
            return False

        return True

    # end method definition

    def authenticate(self, revalidate: bool = False) -> dict | None:
        """Authenticates at Content Server and retrieve OTCS Ticket.

        Args:
            revalidate (bool, optional): determinse if a re-athentication is enforced
                                         (e.g. if session has timed out with 401 error)
                                         By default we use the OTDS ticket (if exists) for the authentication with OTCS.
                                         This switch allows the forced usage of username / password for the authentication.
        Returns:
            dict: Cookie information of None in case of an error.
                  Also stores cookie information in self._cookie
        """

        # Already authenticated and session still valid?
        if self._cookie and not revalidate:
            logger.info(
                "Session still valid - return existing cookie -> %s",
                str(self._cookie),
            )
            return self._cookie

        otcs_ticket = None

        logger.info("Wait for OTCS to be ready...")
        while not self.is_ready():
            logger.warning(
                "OTCS is not ready to receive requests yet. Waiting 30 seconds..."
            )
            time.sleep(30)

        request_url = self.config()["authenticationUrl"]

        if self._otds_ticket and not revalidate:
            logger.info(
                "Requesting OTCS ticket with OTDS ticket; calling -> %s",
                request_url,
            )
            request_header = {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json",
                "OTDSTicket": self._otds_ticket,
            }

            try:
                response = requests.get(
                    url=request_url, headers=request_header, timeout=10
                )
                if response.ok:
                    otcs_ticket = response.headers.get("OTCSTicket")

            except requests.exceptions.RequestException as exception:
                logger.warning(
                    "Unable to connect to -> %s; error -> %s",
                    request_url,
                    exception.strerror,
                )

        # Check if previous authentication was not successful.
        # Then we do the normal username + password authentication:
        if not otcs_ticket:
            logger.info(
                "Requesting OTCS ticket with User/Password; calling -> %s",
                request_url,
            )

            response = None
            try:
                response = requests.post(
                    url=request_url,
                    data=self.credentials(),  # this includes username + password
                    headers=REQUEST_FORM_HEADERS,
                    timeout=REQUEST_TIMEOUT,
                )
            except requests.exceptions.RequestException as exception:
                logger.warning(
                    "Unable to connect to -> %s; error -> %s",
                    request_url,
                    exception.strerror,
                )
                logger.warning("OTCS service may not be ready yet.")
                return None

            if response.ok:
                authenticate_dict = self.parse_request_response(
                    response, "This can be normal during restart", False
                )
                if not authenticate_dict:
                    return None
                else:
                    otcs_ticket = authenticate_dict["ticket"]
                    logger.info("Ticket -> %s", otcs_ticket)
            else:
                logger.error(
                    "Failed to request an OTCS ticket; error -> %s", response.text
                )
                return None

        # Store authentication ticket:
        self._cookie = {"otcsticket": otcs_ticket, "LLCookie": otcs_ticket}
        self._otcs_ticket = otcs_ticket

        return self._cookie

    # end method definition

    def get_server_info(self) -> dict | None:
        """Get Content Server information (server info)

        Args:
            None
        Returns:
            dict: server information or None if the call fails

            Example response:
            {
                'mobile': {
                    'cs_viewer_support': False,
                    'offline_use': True
                },
                'server': {
                    'advanced_versioning': True,
                    'character_encoding': 1,
                    'current_date': '2023-09-05T17:09:41',
                    'current_locale_suffix': '_en_US',
                    'domain_access_enabled': False,
                    'enhanced_advanced_versioning': False,
                    'force_download_for_mime_types': [...],
                    'language_code': 'USA',
                    'languages': [...],
                    'metadata_languages: [...],
                    'url': 'https://otcs.dev.idea-te.eimdemo.com/cs/cs'
                    'version': '23.3'
                    ...
                },
                'sessions': {
                    'enabled': True,
                    'expire_after_last_login': False,
                    'expire_after_last_request': True,
                    'logout_url': '?func=ll.DoLogout&secureRequestToken=LUAQSY%2BJs4KnlwoVgxLtxQFYrov2XefJQM9ShyhOK93Mzp3ymCxX6IGMTtUgNvTH7AYVt%2BbWLEw%3D',
                    'session_inactivity': 7020000,
                    'session_reaction_time': 180000,
                    'session_timeout': 7200000
                },
                'viewer': {
                    'content_suite': {...}
                }
            }
        """

        request_url = self.config()["serverInfoUrl"]
        request_header = self._cookie

        logger.info(
            "Retrieve Extended ECM server information; calling -> %s", request_url
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to retrieve Extended ECM server information; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_server_version(self) -> str | None:
        """Get Content Server version

        Args:
            None
        Returns:
            str: server version number like 23.4
        """

        response = self.get_server_info()
        if not response:
            return None

        server_info = response.get("server")
        if not server_info:
            return None

        return server_info.get("version")

    # end method definition

    def apply_config(self, xml_file_path: str) -> dict | None:
        """Apply Content Server administration settings from XML file

        Args:
            xml_file_path (str): name + path of the XML settings file
        Returns:
            dict: Import response or None if the import fails.
                  The field response["results"]["data"]["restart"] indicates if the settings
                  require a restart of the OTCS services.
        """

        filename = os.path.basename(xml_file_path)

        if not os.path.exists(xml_file_path):
            logger.error(
                "The admin settings file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(xml_file_path),
            )
            return None

        llconfig_file = {
            "file": (filename, open(file=xml_file_path, encoding="utf-8"), "text/xml")
        }

        request_url = self.config()["importSettingsUrl"]
        request_header = self._cookie

        logger.info(
            "Applying admin settings from file -> %s; calling -> %s",
            xml_file_path,
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                files=llconfig_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                logger.debug(
                    "Admin settings in file -> %s have been applied", xml_file_path
                )
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import settings file -> %s; status -> %s; error -> %s",
                    xml_file_path,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_user(self, name: str, show_error: bool = False) -> dict | None:
        """Lookup Extended ECM user based on the name.

        Args:
            name (str): name of the user
            show_error (bool): treat as error if user is not found
        Returns:
            dict: User information or None if the user is not found.
            The returned information has a structure like this:

            {
                'collection':
                {
                    'paging': {...},
                    'sorting': {...}
                },
                'links':
                {
                    'data': {...}
                },
                'results': [
                    {
                        'data':
                        {
                            {
                                'birth_date': None,
                                'business_email': 'pramos@M365x61936377.onmicrosoft.com',
                                'business_fax': None,
                                'business_phone': None,
                                'cell_phone': None,
                                'deleted': False,
                                'display_language': None,
                                'first_name': 'Peter',
                                'gender': None,
                                'group_id': 8006,
                                'home_address_1': None,
                                'home_address_2': None,
                                'home_fax': None,
                                'home_phone': None,
                                'id': 8123,
                                'initials': None,
                                'last_name': 'Ramos',
                                'middle_name': None,
                                'name': 'pramos',
                                'name_formatted': 'Peter Ramos',
                                ...
                                'photo_id': 13981,
                                'photo_url': 'api/v1/members/8123/photo?v=13981.1'
                                ...
                                'type'; 0,
                                'type_name': 'User'
                                }
                        }
                    }
                ]
            }
            To access the (login) name of the first user found use ["results"][0]["data"]["properties"]["name"].
            It is easier to use the method get_result_value(response, "name", 0)
        """

        # Add query parameters (these are NOT passed via JSon body!)
        # type = 0 ==> User
        request_url = self.config()["membersUrlv2"] + "?where_type=0&query={}".format(
            name
        )
        request_header = self.request_form_header()

        logger.info("Get user with name -> %s; calling -> %s", name, request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to get user -> %s; status -> %s; error -> %s",
                        name,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info("User -> %s not found.", name)
                return None

    # end method definition

    def add_user(
        self,
        name: str,
        password: str,
        first_name: str,
        last_name: str,
        email: str,
        title: str,
        base_group: int,
        privileges: list | None = None,
    ) -> dict | None:
        """Add Content Server user.

        Args:
            name (str): login name of the user
            password (str): password of the user
            first_name (str): first name of the user
            last_name (str): last name of the user
            email (str): email address of the user
            title (str): title of the user
            base_group (int): base group id of the user (e.g. department)
            privileges (list, optional): values are Login, Public Access, Content Manager,
                                         Modify Users, Modify Groups, User Admin Rights,
                                         Grant Discovery, System Admin Rights
        Returns:
            dict: User information or None if the user couldn't be created (e.g. because it exisits already).
        """

        if privileges is None:
            privileges = ["Login", "Public Access"]

        user_post_body = {
            "type": 0,
            "name": name,
            "password": password,
            "first_name": first_name,
            "last_name": last_name,
            "business_email": email,
            "title": title,
            "group_id": base_group,
            "privilege_login": ("Login" in privileges),
            "privilege_public_access": ("Public Access" in privileges),
            "privilege_content_manager": ("Content Manager" in privileges),
            "privilege_modify_users": ("Modify Users" in privileges),
            "privilege_modify_groups": ("Modify Groups" in privileges),
            "privilege_user_admin_rights": ("User Admin Rights" in privileges),
            "privilege_grant_discovery": ("Grant Discovery" in privileges),
            "privilege_system_admin_rights": ("System Admin Rights" in privileges),
        }

        request_url = self.config()["membersUrlv2"]
        request_header = self.request_form_header()

        logger.info("Adding user -> %s; calling -> %s", name, request_url)

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=user_post_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to add user -> %s; status -> %s; error -> %s",
                    name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def search_user(self, value: str, field: str = "where_name") -> dict | None:
        """Find a user based on search criteria.

        Args:
            value (str): field value
            field (str): user field to search with (where_name, where_first_name, where_last_name)
        Returns:
            dict: User information or None if the user couldn't be found (e.g. because it doesn't exist).

            Example response:
            {
                'collection': {
                    'paging': {...},
                    'sorting': {...}
                },
                'links': {
                    'data': {...}
                },
                'results': [
                    {
                        'data': {
                            'properties': {
                                'birth_date': None,
                                'business_email': 'dfoxhoven@M365x61936377.onmicrosoft.com',
                                'business_fax': None,
                                'business_phone': None,
                                'cell_phone': None,
                                'deleted': False,
                                'display_language': None,
                                'first_name': 'Deke',
                                'gender': None,
                                'group_id': 8005,
                                'home_address_1': None,
                                'home_address_2': None,
                                'home_fax': None,
                                'home_phone': None,
                                'id': 8562,
                                'initials': 'DF',
                                'last_name': 'Foxhoven',
                                'middle_name': None,
                                'name': 'dfoxhoven',
                                'name_formatted': 'Deke Foxhoven',
                                ...
                            }
                        }
                    }
                ]
            }
        """

        request_url = self.config()["membersUrlv2"] + "?" + field + "=" + value
        request_header = self.request_form_header()

        logger.info(
            "Searching user by field -> %s, value -> %s; calling -> %s",
            field,
            value,
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Cannot find user with -> %s = %s; status -> %s; error -> %s",
                    field,
                    value,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def update_user(self, user_id: int, field: str, value: str) -> dict | None:
        """Update a defined field for a user.

        Args:
            user_id (int): ID of the user
            value (str): field value
            field (str): user field
        Returns:
            dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).
        """

        user_put_body = {field: value}

        request_url = self.config()["membersUrlv2"] + "/" + str(user_id)
        request_header = self.request_form_header()

        logger.info(
            "Updating user with ID -> %s, field -> %s, value -> %s; calling -> %s",
            str(user_id),
            field,
            value,
            request_url,
        )
        logger.debug("User Attributes -> %s", str(user_put_body))

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                data=user_put_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update user with ID -> %s; status -> %s; error -> %s",
                    str(user_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_user_profile(self) -> dict | None:
        """Update a defined field for a user profile.
           IMPORTANT: this method needs to be called by the authenticated user

        Args:
            field (str): user profile field
            value (str): new field value
        Returns:
            dict: User information or None if the user couldn't be updated
                  (e.g. because it doesn't exist).
        """

        request_url = self.config()["membersUrlv2"] + "/preferences"
        request_header = self.request_form_header()

        logger.info(
            "Get profile (settings) for current user; calling -> %s",
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get profile of current user; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def update_user_profile(
        self, field: str, value: str, config_section: str = "SmartUI"
    ) -> dict | None:
        """Update a defined field for a user profile.
           IMPORTANT: this method needs to be called by the authenticated user

        Args:
            field (str): user profile field
            value (str): new field value
            config_section (str, optional): name of the config section. Possible config_section values:
                                            * SmartUI
                                            * General
                                            * Colors
                                            * ContentIntelligence
                                            * Discussion
                                            * Follow Up
                                            * Template Workspaces
                                            * Workflow
                                            * XECMGOVSettings
                                            * CommunitySettings
                                            * RecMan
                                            * PhysObj
        Returns:
            dict: User information or None if the user couldn't be updated
                  (e.g. because it doesn't exist).
        """

        user_profile_put_body = {config_section: {field: value}}

        request_url = self.config()["membersUrlv2"] + "/preferences"
        request_header = self.request_form_header()

        logger.info(
            "Updating profile for current user, field -> %s, value -> %s; calling -> %s",
            field,
            value,
            request_url,
        )
        logger.debug("User Attributes -> %s", str(user_profile_put_body))

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.put(
                url=request_url,
                data={"body": json.dumps(user_profile_put_body)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update profile of current user; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def update_user_photo(self, user_id: int, photo_id: int) -> dict | None:
        """Update a user with a profile photo (which must be an existing node).

        Args:
            user_id (int): ID of the user
            photo_id (int): Node ID of the photo
        Returns:
            dict: Node information or None if photo node is not found.
        """

        update_user_put_body = {"photo_id": photo_id}

        request_url = self.config()["membersUrl"] + "/" + str(user_id)
        request_header = self.request_form_header()

        logger.info(
            "Update user ID -> %s with photo ID -> %s; calling -> %s",
            user_id,
            photo_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                data=update_user_put_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update user with ID -> %s; status -> %s; error -> %s",
                    str(user_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def is_proxy(self, user_name: str) -> bool:
        """Check if a user is defined as proxy of the current user.
           This method differentiates between the old (xGov) based
           implementation and the new Extended ECM platform one
           that was introduced with version 23.4.

        Args:
            user_name (str): user  to test (login name)
        Returns:
            bool: True is user is proxy of current user. False if not.
        """

        version_number = self.get_server_version()
        # Split the version number by dot
        parts = version_number.split(".")
        # Take the first two parts and join them back with a dot
        stripped_version = ".".join(parts[:2])

        try:
            version_number = float(stripped_version)
        except ValueError:
            version_number = 99.99  # Set to version 99.99 for "main"

        if version_number >= 23.4:
            response = self.get_user_proxies(use_v2=True)
            if self.exist_result_item(
                response=response, key="name", value=user_name, property_name=""
            ):
                return True
            else:
                return False
        else:
            response = self.get_user_proxies(use_v2=False)
            if not response or not "proxies" in response:
                return False
            proxies = response["proxies"]

            for proxy in proxies:
                if proxy["name"] == user_name:
                    return True
            return False

    # end method definition

    def get_user_proxies(self, use_v2: bool = False) -> dict | None:
        """Get list of user proxies.
           This method needs to be called as the user the proxy is acting for.
        Args:
            None
        Returns:
            dict: Node information or None if REST call fails.
        """

        if use_v2:
            request_url = self.config()["membersUrlv2"] + "/proxies"
        else:
            request_url = self.config()["membersUrl"] + "/proxies"
        request_header = self.request_form_header()

        logger.info("Get proxy users for current user; calling -> %s", request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get proxy users for current user; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def add_user_proxy(
        self,
        proxy_user_id: int,
        from_date: str = None,
        to_date: str = None,
    ) -> dict | None:
        """Add a user as a proxy user to the current user.
           IMPORTANT: This method needs to be called as the user the proxy is acting for.
           Optional this method can be provided with a time span the proxy should be active.
           This method differentiates between the old (xGov) based
           implementation and the new Extended ECM platform one
           that was introduced with version 23.4.

           Example payload for proxy user 19340 without time span:
           {"id":2545, "from_date": None, "to_date": None}

           Example payload for proxy user 19340 with time span:
           {"id":2545, "from_date":"2023-03-15", "to_date":"2023-03-31"}

        Args:
            user_id (int): ID of the user
            from_date (str, optional): start date for proxy (format YYYY-MM-DD)
            to_date (str, optional): end date for proxy (format YYYY-MM-DD)
        Returns:
            dict: Request response or None if call fails.
        """

        version_number = self.get_server_version()
        # Split the version number by dot
        parts = version_number.split(".")
        # Take the first two parts and join them back with a dot
        stripped_version = ".".join(parts[:2])
        version_number = float(stripped_version)

        # for versions older than 23.4 we need to use
        # the egacy Extended ECM for Government Proxy
        # implementation:
        if version_number >= 23.4:
            post_dict = {}
            post_dict["id"] = proxy_user_id
            post_dict["from_date"] = from_date
            post_dict["to_date"] = to_date
            post_data = {"body": json.dumps(post_dict)}
            request_url = self.config()["membersUrlv2"] + "/proxies"
            logger.info(
                "Assign proxy user with ID -> %s to current user; calling -> %s",
                proxy_user_id,
                request_url,
            )
        else:
            post_dict = {}
            if from_date and to_date:
                post_dict["from_date"] = from_date
                post_dict["to_date"] = to_date
            post_dict = {str(proxy_user_id): post_dict}
            post_data = {"add_proxy": json.dumps(post_dict)}
            request_url = self.config()["membersUrl"] + "/proxies"
            logger.info(
                "Assign proxy user with ID -> %s to current user (legacy xGov); calling -> %s",
                proxy_user_id,
                request_url,
            )

        request_header = self.request_form_header()

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.post(
                url=request_url,
                data=post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign proxy user with ID -> %s to current user; status -> %s; error -> %s",
                    proxy_user_id,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def add_favorite(self, node_id: int) -> dict | None:
        """Add a favorite for the current (authenticated) user.

        Args:
            node_id (int): ID of the node.
        Returns:
            dict: Request response or None if the favorite creation has failed.
        """

        request_url = self.config()["favoritesUrl"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.info(
            "Adding favorite for node ID -> %s; calling -> %s", node_id, request_url
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to add favorite for node ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def add_favorite_tab(self, tab_name: str, order: int) -> dict | None:
        """Add a favorite tab for the current (authenticated) user.

        Args:
            tab_name (str): Name of the new tab.
            order (int): The order of the tab.
        Returns:
            dict: Request response or None if the favorite tab creation has failed.
        """

        favorite_tab_post_body = {"name": tab_name, "order": str(order)}

        request_url = self.config()["favoritesUrl"] + "/tabs"
        request_header = self.request_form_header()

        logger.info("Adding favorite tab -> %s; calling -> %s", tab_name, request_url)

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=favorite_tab_post_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to add favorite tab -> %s; status -> %s; error -> %s",
                    tab_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_group(self, name: str, show_error: bool = False) -> dict | None:
        """Lookup Content Server group.

        Args:
            name (str): name of the group
            show_error (bool): if True, treat as error if group is not found
        Returns:
            dict: Group information or None if the group is not found.
            The returned information has a structure like this:
            "data": [
                {
                    "id": 0,
                    "name": "string",
                    ...
                }
            ]
            To access the id of the first group found use ["data"][0]["id"]
        """

        # Add query parameters (these are NOT passed via JSon body!)
        # type = 1 ==> Group
        request_url = self.config()["membersUrlv2"] + "?where_type=1&query={}".format(
            name
        )
        request_header = self.request_form_header()

        logger.info("Get group with name -> %s; calling -> %s", name, request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to get group -> %s; status -> %s; error -> %s",
                        name,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info("Group -> %s not found.", name)
                return None

    # end method definition

    def add_group(self, name: str) -> dict | None:
        """Add Content Server group.

        Args:
            name (str): name of the group
        Returns:
            dict: Group information or None if the group couldn't be created (e.g. because it exisits already).
        """

        group_post_body = {"type": 1, "name": name}

        request_url = self.config()["membersUrlv2"]
        request_header = self.request_form_header()

        logger.info("Adding group -> %s; calling -> %s", name, request_url)
        logger.debug("Group Attributes -> %s", str(group_post_body))

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=group_post_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to add group -> %s; status -> %s; error -> %s",
                    name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_group_members(
        self, group: int, member_type: int, limit: int = 100
    ) -> dict | None:
        """Get Content Server group members.

        Args:
            group (int): ID of the group.
            member_type (int): users = 0, groups = 1
            limit (int, optional): max number of results (internal default is 25)
        Returns:
            dict: Group members or None if the group members couldn't be found.
        """

        # default limit is 25 which may not be enough for groups with many members
        # where_type = 1 makes sure we just get groups and not users
        request_url = (
            self.config()["membersUrlv2"]
            + "/"
            + str(group)
            + "/members?where_type="
            + str(member_type)
            + "&limit="
            + str(limit)
        )
        request_header = self.request_form_header()

        logger.info(
            "Getting members of group with ID -> %s; calling -> %s",
            str(group),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get members of group -> %s; status -> %s; error -> %s",
                    str(group),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def add_group_member(self, member_id: int, group_id: int) -> dict | None:
        """Add a user or group to a target group.

        Args:
            member_id (int): ID of the user or group to add.
            group_id (int): ID of the target group.
        Returns:
            dict: Response or None if adding a the member fails.
        """

        group_member_post_body = {"member_id": member_id}

        request_url = self.config()["membersUrlv2"] + "/" + str(group_id) + "/members"
        request_header = self.request_form_header()

        logger.info(
            "Adding member with ID -> %s to group with ID -> %s; calling -> %s",
            str(member_id),
            str(group_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=group_member_post_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to add member with ID -> %s to group with ID -> %s; status -> %s; error -> %s",
                    str(member_id),
                    str(group_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_node(self, node_id: int, timeout: int = REQUEST_TIMEOUT) -> dict | None:
        """Get a node based on the node ID.

        Args:
            node_id (int) is the node Id of the node
            timeout (int, optional): timeout for the request in seconds
        Returns:
            dict: Node information or None if no node with this ID is found.
            "results": [
                {
                    "data": [
                        {
                            "columns": [
                                {
                                "data_type": 0,
                                "key": "string",
                                "name": "string",
                                "sort_key": "string"
                                }
                            ],
                            "properties": [
                                {
                                    "advanced_versioning": true,
                                    "container": true,
                                    "container_size": 0,
                                    "create_date": "string",
                                    "create_user_id": 0,
                                    "description": "string",
                                    "description_multilingual": {
                                        "en": "string",
                                        "de": "string"
                                    },
                                    "external_create_date": "2019-08-24",
                                    "external_identity": "string",
                                    "external_identity_type": "string",
                                    "external_modify_date": "2019-08-24",
                                    "external_source": "string",
                                    "favorite": true,
                                    "guid": "string",
                                    "hidden": true,
                                    "icon": "string",
                                    "icon_large": "string",
                                    "id": 0,
                                    "modify_date": "2019-08-24",
                                    "modify_user_id": 0,
                                    "name": "string",
                                    "name_multilingual": {
                                        "en": "string",
                                        "de": "string"
                                    },
                                    "owner": "string",
                                    "owner_group_id": 0,
                                    "owner_user_id": 0,
                                    "parent_id": 0,
                                    "reserved": true,
                                    "reserved_date": "string",
                                    "reserved_user_id": 0,
                                    "status": 0,
                                    "type": 0,
                                    "type_name": "string",
                                    "versionable": true,
                                    "versions_control_advanced": true,
                                    "volume_id": 0
                                }
                            ]
                        }
                    ]
                }
            ]
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.info("Get node with ID -> %s; calling -> %s", str(node_id), request_url)

        retries = 0
        while True:
            try:
                response = requests.get(
                    url=request_url,
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=timeout,
                )
                if response.ok:
                    return self.parse_request_response(response)
                # Check if Session has expired - then re-authenticate and try once more
                elif response.status_code == 401 and retries == 0:
                    logger.warning("Session has expired - try to re-authenticate...")
                    self.authenticate(revalidate=True)
                    retries += 1
                else:
                    logger.error(
                        "Failed to get node with ID -> %s; status -> %s; error -> %s",
                        str(node_id),
                        response.status_code,
                        response.text,
                    )
                    return None
            except requests.exceptions.Timeout:
                if retries <= REQUEST_MAX_RETRIES:
                    logger.warning(
                        "Request timed out. Retrying in %s seconds...",
                        str(REQUEST_RETRY_DELAY),
                    )
                    retries += 1
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    logger.error(
                        "Failed to get node with ID -> %s; timeout error", str(node_id)
                    )
                    # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                    logger.warning("Turn timeouts off and wait forever...")
                    timeout = None

    # end method definition

    def get_node_by_parent_and_name(
        self,
        parent_id: int,
        name: str,
        fields: str = "properties",
        show_error: bool = False,
    ) -> dict | None:
        """Get a node based on the parent ID and name. This method does basically
           a query with "where_name" and the "result" is a list.

        Args:
            parent_id (int) is the node Id of the parent node
            name (str) is the name of the node to get
            fields (str, optional): which fields to retrieve. This can have a big impact on performance!
            show_error (bool, optional): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this name is found in parent.
                        Access to node ID with: response["results"][0]["data"]["properties"]["id"]
        """

        # Add query parameters (these are NOT passed via JSon body!)
        query = {"where_name": name}
        if fields:
            query["fields"] = fields
        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(parent_id)
            + "/nodes?{}".format(encoded_query)
        )
        request_header = self.request_form_header()

        logger.info(
            "Get node with name -> %s and parent ID -> %s; calling -> %s",
            name,
            str(parent_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to get node with name -> %s and parent ID -> %s; status -> %s; error -> %s",
                        name,
                        str(parent_id),
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info(
                        "Node with name -> %s and parent ID -> %s not found.",
                        name,
                        str(parent_id),
                    )
                return None

    # end method definition

    def get_node_by_workspace_and_path(
        self, workspace_id: int, path: list, show_error: bool = False
    ) -> dict | None:
        """Get a node based on the workspace ID (= node ID) and path (list of folder names).

        Args:
            workspace_id (int): node ID of the workspace
            path (list): list of container items (top down), last item is name of to be retrieved item.
                         If path is empty the node of the volume is returned.
            show_error (bool, optional): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this path is found.
        """

        current_item_id = workspace_id

        # in case the path is an empty list
        # we will have the node of the workspace:
        node = self.get_node(current_item_id)

        for path_element in path:
            node = self.get_node_by_parent_and_name(current_item_id, path_element)
            current_item_id = self.get_result_value(node, "id")
            if not current_item_id:
                if show_error:
                    logger.error("Cannot find path element -> %s!", path_element)
                else:
                    logger.info("Cannot find path element -> %s.", path_element)
                return None
            logger.debug(
                "Traversing path element -> %s (%s)", path_element, str(current_item_id)
            )

        return node

    # end method definition

    def get_node_by_volume_and_path(
        self, volume_type: int, path: list | None = None
    ) -> dict | None:
        """Get a node based on the volume and path (list of container items).

        Args:
            volume_type (int): Volume type ID (default is 141 = Enterprise Workspace)
                "Records Management"                = 550
                "Content Server Document Templates" = 20541
                "O365 Office Online Volume"         = 1296
                "Categories Volume"                 = 133
                "Perspectives"                      = 908
                "Perspective Assets"                = 954
                "Facets Volume"                     = 901
                "Transport Warehouse"               = 525
                "Transport Warehouse Workbench"     = 528
                "Transport Warehouse Package"       = 531
                "Event Action Center Configuration" = 898
                "Classification Volume"             = 198
                "Support Asset Volume"              = 1309
                "Physical Objects Workspace"        = 413
                "Extended ECM"                      = 882
                "Enterprise Workspace"              = 141
                "Personal Workspace"                = 142
                "Business Workspaces"               = 862
            path (list): list of container items (top down), last item is name of to be retrieved item.
                         If path is empty the node of the volume is returned.
        Returns:
            dict: Node information or None if no node with this path is found.
        """

        # If path is not given we use empty list to make the for loop below working in this case as well
        if path is None:
            path = []

        # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
        response = self.get_volume(volume_type)
        if not response:
            logger.error("Volume type -> %s not found!", str(volume_type))
            return None

        volume_id = self.get_result_value(response, "id")
        logger.info(
            "Volume type -> %s has node ID -> %s", str(volume_type), str(volume_id)
        )

        current_item_id = volume_id

        # in case the path is an empty list
        # we will have the node of the volume:
        node = self.get_node(current_item_id)

        for path_element in path:
            node = self.get_node_by_parent_and_name(current_item_id, path_element)
            path_item_id = self.get_result_value(node, "id")
            if not path_item_id:
                logger.error(
                    "Cannot find path element -> %s in container with ID -> %s.",
                    path_element,
                    str(current_item_id),
                )
                return None
            current_item_id = path_item_id
            logger.debug("Traversing path element with ID -> %s", str(current_item_id))

        return node

    # end method definition

    def get_node_from_nickname(
        self, nickname: str, show_error: bool = False
    ) -> dict | None:
        """Get a node based on the nickname.

        Args:
            nickname (str): Nickname of the node.
            show_error (bool): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this nickname is found.
        """

        request_url = self.config()["nicknameUrl"] + "/" + nickname + "/nodes"
        request_header = self.request_form_header()

        logger.info(
            "Get node with nickname -> %s; calling -> %s", nickname, request_url
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to get node with nickname -> %s; status -> %s; error -> %s",
                        nickname,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info("Node with nickname -> %s not found.", nickname)
                return None

    def set_node_nickname(
        self, node_id: int, nickname: str, show_error: bool = False
    ) -> dict | None:
        """Assign a nickname to an Extended ECM node (e.g. workspace)

        Args:
            nickname (str): Nickname of the node.
            show_error (bool): treat as error if node is not found
        Returns:
            dict: Node information or None if no node with this nickname is found.
        """

        nickname_put_body = {"nickname": nickname}

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/nicknames"
        request_header = self.request_form_header()

        logger.info(
            "Assign nickname -> %s to node with ID -> %s; calling -> %s",
            nickname,
            node_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                data=nickname_put_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to assign nickname -> %s to node ID -> %s; status -> %s; error -> %s",
                        nickname,
                        node_id,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info(
                        "Cannot assign nickname -> %s to node ID -> %s. Maybe the nickname is already in use or the node does not exist.",
                        nickname,
                        node_id,
                    )
                return None

    # end method definition

    def get_subnodes(
        self,
        parent_node_id: int,
        filter_node_types: int = -2,
        filter_name: str = "",
        show_hidden: bool = False,
        limit: int = 100,
        page: int = 1,
        fields: str = "properties",  # per default we just get the most important information
    ) -> dict | None:
        """Get a subnodes of a parent node ID.

        Args:
            parent_node_id (int) is the node Id of the node
            filter_node_types (int, optional):
                -1 get all containers
                -2 get all searchable objects (default)
                -3 get all non-containers
            filter_name (str, optional): filter nodes for specific name (dfault = no filter)
            show_hidden (bool, optional): list also hidden items (default = False)
            limit (int, optional): maximum number of results (default = 100)
            page (int, optional): number of result page (default = 1 = 1st page)
            fields (str): which fields to retrieve. This can have a big impact on performance!
        Returns:
            dict: Subnodes information or None if no node with this parent ID is found.
        """

        # Add query parameters (these are NOT passed via JSon body!)
        query = {
            "where_type": filter_node_types,
            "limit": limit,
        }
        if filter_name:
            query["where_name"] = filter_name
        if show_hidden:
            query["show_hidden"] = show_hidden
        if page > 1:
            query["page"] = page
        if fields:
            query["fields"] = fields

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(parent_node_id)
            + "/nodes"
            + "?{}".format(encoded_query)
        )
        request_header = self.request_form_header()

        logger.info(
            "Get subnodes of parent node with ID -> %s; calling -> %s",
            str(parent_node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get subnodes for parent node with ID -> %s; status -> %s; error -> %s",
                    parent_node_id,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_node_actions(self, node_id: int, filter_actions: list = None) -> dict:
        """Get allowed actions for a node.

        Args:
            node_id (int): _description_
            filter_actions (list, optional): _description_

        Returns:
            dict: _description_
        """

        actions_post_body = {"ids": [node_id], "actions": filter_actions}

        request_url = self.config()["nodesUrlv2"] + "/actions"

        request_header = self.request_form_header()

        logger.info(
            "Get actions for node with ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=actions_post_body,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get actions for node with ID -> %s; status -> %s; error -> %s",
                    node_id,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def rename_node(
        self,
        node_id: int,
        name: str,
        description: str,
        name_multilingual: dict | None = None,
        description_multilingual: dict | None = None,
    ) -> dict | None:
        """Change the name and description of a node.

        Args:
            node_id (int): ID of the node. You can use the get_volume() function below to
                               to the node id for a volume.
            name (str): New name of the node.
            description (str): New description of the node.
            name_multilingual (dict, optional): multi-lingual node names
            description_multilingual (dict, optional): multi-lingual description
        Returns:
            dict: Request response or None if the renaming fails.
        """

        rename_node_put_body = {"name": name, "description": description}

        if name_multilingual:
            rename_node_put_body["name_multilingual"] = name_multilingual
        if description_multilingual:
            rename_node_put_body["description_multilingual"] = description_multilingual

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.info(
            "Renaming node with ID -> %s to -> %s; calling -> %s",
            str(node_id),
            name,
            request_url,
        )

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                data={"body": json.dumps(rename_node_put_body)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to rename node with ID -> %s to -> %s; status -> %s; error -> %s",
                    str(node_id),
                    name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_volumes(self) -> dict | None:
        """Get all Volumes.

        Args:
            None
        Returns:
            dict: Volume Details or None if an error occured.
            {
                'links': {
                    'data': {...}
                },
                'results': [
                    {
                        'data': {
                            'properties': {
                                'advanced_versioning': None,
                                'container': True,
                                'container_size': 16,
                                'create_date': '2023-05-07T23:18:50Z',
                                'create_user_id': 1000,
                                'description': '',
                                'description_multilingual': {'de': '', 'en': '', 'fr': '', 'it': '', 'ja': ''},
                                'external_create_date': None,
                                'external_identity': '',
                                'external_identity_type': '',
                                'external_modify_date': None,
                                'external_source': '',
                                'favorite': False,
                                'hidden': False,
                                ...
                                'id': 2000,
                                ...
                                'name': 'Enterprise',
                                'name_multilingual': {'de': '', 'en': 'Enterprise', 'fr': '', 'it': '', 'ja': ''},
                                ...
                                'parent_id': -1,
                                'type': 141,
                                'volume_id': -2000,
                                ...
                            }
                            ...
                        }
                    },
                    ...
                ]
            }
            Example:
            ["results"][0]["data"]["properties"]["id"] is the node ID of the volume.
        """

        request_url = self.config()["volumeUrl"]
        request_header = self.request_form_header()

        logger.info("Get volumes; calling -> %s", request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get volumes; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_volume(
        self, volume_type: int, timeout: int = REQUEST_TIMEOUT
    ) -> dict | None:
        """Get Volume information based on the volume type ID.

        Args:
            volume_type (int): ID of the volume type
            timeout (int, optional): timeout for the request in seconds
        Returns:
            dict: Volume Details or None if volume is not found.
            ["results"]["data"]["properties"]["id"] is the node ID of the volume.
        """

        request_url = self.config()["volumeUrl"] + "/" + str(volume_type)
        request_header = self.request_form_header()

        logger.info(
            "Get volume type -> %s; calling -> %s", str(volume_type), request_url
        )

        retries = 0
        while True:
            try:
                response = requests.get(
                    url=request_url,
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=timeout,
                )
                if response.ok:
                    return self.parse_request_response(response)
                # Check if Session has expired - then re-authenticate and try once more
                elif response.status_code == 401 and retries == 0:
                    logger.warning("Session has expired - try to re-authenticate...")
                    self.authenticate(revalidate=True)
                    retries += 1
                else:
                    logger.error(
                        "Failed to get volume type -> %s; status -> %s; error -> %s",
                        str(volume_type),
                        response.status_code,
                        response.text,
                    )
                    return None
            except requests.exceptions.Timeout:
                if retries <= REQUEST_MAX_RETRIES:
                    logger.warning(
                        "Request timed out. Retrying in %s seconds...",
                        str(REQUEST_RETRY_DELAY),
                    )
                    retries += 1
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    logger.error(
                        "Failed to get volume type -> %s; timeout error",
                        str(volume_type),
                    )
                    # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                    logger.warning("Turn timeouts off and wait forever...")
                    timeout = None

    # end method definition

    def check_node_name(self, parent_id: int, node_name: str) -> dict | None:
        """Check if a node with a given name does already exist under a given parent node.

        Args:
            parent_id (int): ID of the parent location
            node_name (str): name of the new node
        Returns:
            dict | None: if response["results"] contains an element then the node with the name does exist.
                         if not response["results"] then the node with the given name does not exist
                         None in case an error occured
        """

        request_url = self.config()["validationUrl"]
        request_header = self.request_form_header()

        logger.info(
            "Check if node with name -> %s can be created in parent with ID -> %s; calling -> %s",
            node_name,
            str(parent_id),
            request_url,
        )

        check_node_name_post_data = {"parent_id": parent_id, "names": [node_name]}

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data={"body": json.dumps(check_node_name_post_data)},
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to check if node name -> %s can be created in parent with ID -> %s; status -> %s; error -> %s",
                    node_name,
                    str(parent_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def upload_file_to_volume(
        self, package_url: str, file_name: str, mime_type: str, volume_type: int
    ) -> dict | None:
        """Fetch a file from a URL or local filesystem and upload it to a Content Server volume.

        Args:
            package_url (str): URL to download file
            file_name (str): name of the file
            mime_type (str): mimeType of the file
            volume_type (int): type (ID) of the volume
        Returns:
            dict: Upload response or None if the upload fails.
        """

        if package_url.startswith("http"):
            # Download file from remote location specified by the packageUrl
            # this must be a public place without authentication:
            logger.info("Download transport package from URL -> %s", package_url)

            try:
                package = requests.get(url=package_url, timeout=1200)
                package.raise_for_status()
            except requests.exceptions.HTTPError as errh:
                logger.error("Http Error -> %s", errh.strerror)
                return None
            except requests.exceptions.ConnectionError as errc:
                logger.error("Error Connecting -> %s", errc.strerror)
                return None
            except requests.exceptions.Timeout as errt:
                logger.error("Timeout Error -> %s", errt.strerror)
                return None
            except requests.exceptions.RequestException as err:
                logger.error("Request error -> %s", err.strerror)
                return None

            logger.info(
                "Successfully downloaded package -> %s; status code -> %s",
                package_url,
                package.status_code,
            )
            file = package.content

        elif os.path.exists(package_url):
            logger.info("Using local package -> %s", package_url)
            file = open(file=package_url, mode="rb")

        else:
            logger.warning("Cannot access -> %s", package_url)
            return None

        upload_post_data = {"type": str(volume_type), "name": file_name}
        upload_post_files = [("file", (f"{file_name}", file, mime_type))]

        request_url = self.config()["nodesUrlv2"]
        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 500 response

        logger.info(
            "Uploading package -> %s with mime type -> %s; calling -> %s",
            file_name,
            mime_type,
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=upload_post_data,
                files=upload_post_files,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to upload file -> %s to volume of type -> %s; status -> %s; error -> %s",
                    package_url,
                    str(volume_type),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def upload_file_to_parent(
        self, file_url: str, file_name: str, mime_type: str, parent_id: int
    ) -> dict | None:
        """Fetch a file from a URL or local filesystem and upload it to a Content Server parent (folder).

        Args:
            file_url (str): URL to download file or local file
            file_name (str): name of the file
            mime_type (str): mimeType of the file
            parent_id (int): parent (ID) of the file to upload
        Returns:
            dict: Upload response or None if the upload fails.
        """

        if file_url.startswith("http"):
            # Download file from remote location specified by the file_url parameter
            # this must be a public place without authentication:
            logger.info("Download file from URL -> %s", file_url)

            try:
                response = requests.get(url=file_url, timeout=1200)
                response.raise_for_status()
            except requests.exceptions.HTTPError as errh:
                logger.error("Http Error -> %s", errh.strerror)
                return None
            except requests.exceptions.ConnectionError as errc:
                logger.error("Error Connecting -> %s", errc.strerror)
                return None
            except requests.exceptions.Timeout as errt:
                logger.error("Timeout Error -> %s", errt.strerror)
                return None
            except requests.exceptions.RequestException as err:
                logger.error("Request error -> %s", err.strerror)
                return None

            logger.info(
                "Successfully downloaded file -> %s; status code -> %s",
                file_url,
                response.status_code,
            )
            file_content = response.content

        elif os.path.exists(file_url):
            logger.info("Uploading local file -> %s", file_url)
            file_content = open(file=file_url, mode="rb")

        else:
            logger.warning("Cannot access -> %s", file_url)
            return None

        upload_post_data = {
            "type": str(144),
            "name": file_name,
            "parent_id": str(parent_id),
        }
        upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

        request_url = self.config()["nodesUrlv2"]
        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 500 response

        logger.info(
            "Uploading file -> %s with mime type -> %s to parent with ID -> %s; calling -> %s",
            file_name,
            mime_type,
            str(parent_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=upload_post_data,
                files=upload_post_files,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to upload file -> %s to parent -> %s; status -> %s; error -> %s",
                    file_url,
                    str(parent_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def add_document_version(
        self,
        node_id: int,
        file_url: str,
        file_name: str,
        mime_type: str = "text/plain",
        description: str = "",
    ) -> dict | None:
        """Fetch a file from a URL or local filesystem and upload it as a new document version.

        Args:
            node_id (int): ID of the document to add add version to
            file_url (str): URL to download file or local file
            file_name (str): name of the file
            mime_type (str, optional): mimeType of the file (default = text/plain)
            description (str, optional): description of the version (default = no description)
        Returns:
            dict: Add version response or None if the upload fails.
        """

        if file_url.startswith("http"):
            # Download file from remote location specified by the file_url parameter
            # this must be a public place without authentication:
            logger.info("Download file from URL -> %s", file_url)

            try:
                response = requests.get(
                    url=file_url,
                    timeout=None,
                )
                response.raise_for_status()
            except requests.exceptions.HTTPError as errh:
                logger.error("Http Error -> %s", errh.strerror)
                return None
            except requests.exceptions.ConnectionError as errc:
                logger.error("Error Connecting -> %s", errc.strerror)
                return None
            except requests.exceptions.Timeout as errt:
                logger.error("Timeout Error -> %s", errt.strerror)
                return None
            except requests.exceptions.RequestException as err:
                logger.error("Request error -> %s", err.strerror)
                return None

            logger.info(
                "Successfully downloaded file -> %s; status code -> %s",
                file_url,
                response.status_code,
            )
            file_content = response.content

        elif os.path.exists(file_url):
            logger.info("Uploading local file -> %s", file_url)
            file_content = open(file=file_url, mode="rb")

        else:
            logger.warning("Cannot access -> %s", file_url)
            return None

        upload_post_data = {"description": description}
        upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/versions"
        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 500 response

        logger.info(
            "Uploading file -> %s with mime type -> %s as new version to document node with ID -> %s; calling -> %s",
            file_name,
            mime_type,
            node_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=upload_post_data,
                files=upload_post_files,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to add file -> %s as new version to document with ID -> %s; status -> %s; error -> %s",
                    file_url,
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_latest_document_version(self, node_id: int) -> dict | None:
        """Get latest version of a document node based on the node ID.

        Args:
            node_id (int) is the node Id of the node
        Returns:
            dict: Node information or None if no node with this ID is found.
        """

        request_url = (
            self.config()["nodesUrl"] + "/" + str(node_id) + "/versions/latest"
        )
        request_header = self.request_form_header()

        logger.info(
            "Get latest version of document with node ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get latest version of document with node ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_document_content(self, node_id: int, version_number: str = "") -> bytes:
        """Get document content from Extended ECM.

        Args:
            node_id (int): node ID of the document to download
            version_number (str, optional): version of the document to download.
                                            If version = "" then download the latest
                                            version.
        Returns:
            bytes: content of the file or None in case of an error.
        """

        if not version_number:
            response = self.get_latest_document_version(node_id)
            if not response:
                logger.error(
                    "Cannot get latest version of document with ID -> %s", str(node_id)
                )
            version_number = response["data"]["version_number"]

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/versions/"
            + str(version_number)
            + "/content"
        )
        request_header = self.request_download_header()

        logger.info(
            "Retrieve document with node ID -> %s and version -> %s; calling -> %s",
            str(node_id),
            str(version_number),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                content = response.content
                break
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to download document with node ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

        return content

        # end method definition

    def download_document(
        self, node_id: int, file_path: str, version_number: str = ""
    ) -> bool:
        """Download a document from Extended ECM to local file system.

        Args:
            node_id (int): node ID of the document to download
            file_path (str): local file path (directory)
            version_number (str): version of the document to download.
                                     If version = "" then download the latest
                                     version.
        Returns:
            bool: True if the document has been download to the specified file.
                     False otherwise.
        """

        directory = os.path.dirname(file_path)
        if not os.path.exists(directory):
            logger.error("Directory -> %s does not exist", directory)
            return False

        if not version_number:
            response = self.get_latest_document_version(node_id)
            if not response:
                logger.error(
                    "Cannot get latest version of document with ID -> %s", str(node_id)
                )
            version_number = response["data"]["version_number"]

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/versions/"
            + str(version_number)
            + "/content"
        )
        request_header = self.request_download_header()

        logger.info(
            "Download document with node ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                content = response.content
                break
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to download document with node ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return False

        logger.info("Writing document content to file -> %s", file_path)

        # Open file in write binary mode
        with open(file=file_path, mode="wb") as file:
            # Write the content to the file
            file.write(content)

        return True

        # end method definition

    def download_config_file(
        self, otcs_url_suffix: str, file_path: str, search: str = "", replace: str = ""
    ) -> bool:
        """Download a config file from a given OTCS URL. This is NOT
            for downloading documents from within the OTCS repository
            but for configuration files such as app packages for MS Teams.

        Args:
            otcs_url_suffix (str): OTCS URL suffix starting typically starting
                                      with /cs/cs?func=,
                                      e.g. /cs/cs?func=officegroups.DownloadTeamsPackage
            file_path (str): local path to save the file (direcotry + filename)
            search (str, optional): optional string to search for a replacement
            replace (str, optional): optional replacement
        Returns:
            bool: True if the download succeeds, False otherwise
        """

        request_url = self.config()["baseUrl"] + otcs_url_suffix
        # request_header = self.cookie()
        request_header = self.request_download_header()

        logger.info("Download config file from URL -> %s", request_url)

        try:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=REQUEST_TIMEOUT,
            )
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return False
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return False
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return False
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return False

        content = response.content

        if search:
            logger.info(
                "Search for all occurances of %s in the config file and replace them with %s",
                search,
                replace,
            )
            content = content.replace(search.encode("utf-8"), replace.encode("utf-8"))

        # Open file in write binary mode
        with open(file=file_path, mode="wb") as file:
            # Write the content to the file
            file.write(content)

        logger.info(
            "Successfully downloaded config file -> %s to -> %s; status code -> %s",
            request_url,
            file_path,
            response.status_code,
        )

        return True

    # end method definition

    def search(
        self,
        search_term: str,
        look_for: str = "complexQuery",
        modifier: str = "",
        slice_id: int = 0,
        query_id: int = 0,
        template_id: int = 0,
        limit: int = 100,
        page: int = 1,
    ) -> dict | None:
        """Search for a search term.

        Args:
            search_term (str), e.g. "test or OTSubType: 189"
            look_for (str, optional): 'allwords', 'anywords', 'exactphrase', and 'complexquery'.
                                      If not specified, it defaults to 'complexQuery'.
            modifier (str, optional): 'synonymsof', 'relatedto', 'soundslike', 'wordbeginswith',
                                      and 'wordendswith'.
                                      If not specified or specify any value other than the available options,
                                      it will be ignored.
            slice_id (int, optional): ID of an existing search slice
            query_id (int, optional): ID of an saved search query
            template_id (int, optional): ID of an saved search template
            limit (int, optional): maximum number of results (default = 100)
            page (int, optional): number of result page (default = 1 = 1st page)
        Returns:
            dict: search response or None if the search fails.
        """

        search_post_body = {
            "where": search_term,
            "lookfor": look_for,
            "page": page,
            "limit": limit,
        }

        if modifier:
            search_post_body["modifier"] = modifier
        if slice_id > 0:
            search_post_body["slice_id"] = slice_id
        if query_id > 0:
            search_post_body["query_id"] = query_id
        if template_id > 0:
            search_post_body["template_id"] = template_id

        request_url = self.config()["searchUrl"]
        request_header = self.request_form_header()

        logger.info("Search for term -> %s; calling -> %s", search_term, request_url)

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=search_post_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to search for term -> %s; status -> %s; error -> %s",
                    search_term,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_external_system_connection(
        self, connection_name: str, show_error: bool = False
    ) -> dict | None:
        """Get Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

        Args:
            connection_name (str): Name of the connection
            show_error (bool, optional): If True, treat as error if connection is not found.
        Returns:
            dict: External system Details or None if the REST call fails.
        """

        request_url = (
            self.config()["externalSystemUrl"] + "/" + connection_name + "/config"
        )
        request_header = self.cookie()

        logger.info(
            "Get external system connection -> %s; calling -> %s",
            connection_name,
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to get external system connection -> %s; status -> %s; error -> %s",
                        connection_name,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info("External system -> %s not found.", connection_name)
                return None

    # end method definition

    def add_external_system_connection(
        self,
        connection_name: str,
        connection_type: str,
        as_url: str,
        base_url: str,
        username: str,
        password: str,
        authentication_method: str = "BASIC",  # either BASIC or OAUTH
        client_id: str = None,
        client_secret: str = None,
    ) -> dict | None:
        """Add Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

        Args:
            connection_name (str): Name of the connection
            connection_type (str): Type of the connection (HTTP, SF, SFInstance)
            as_url (str): Application URL of the external system
            base_url (str): Base URL of the external system
            username (str): username (used for BASIC authentication)
            password (str): password (used for BASIC authentication)
            authentication_method (str, optional): either BASIC (using username and password) or OAUTH
            client_id (str, optional): OAUTH Client ID (only required if authenticationMethod = OAUTH)
            client_secret (str, optional): OAUTH Client Secret (only required if authenticationMethod = OAUTH)
        Returns:
            dict: External system Details or None if the REST call fails.
        """

        external_system_post_body = {
            "external_system_name": connection_name,
            "conn_type": connection_type,
            "asurl": as_url,
            "baseurl": base_url,
            "username": username,
            "password": password,
        }

        if authentication_method == "OAUTH" and client_id and client_secret:
            external_system_post_body["authentication_method"] = str(
                authentication_method
            )
            external_system_post_body["client_id"] = str(client_id)
            external_system_post_body["client_secret"] = str(client_secret)

        request_url = self.config()["externalSystemUrl"]
        request_header = self.cookie()

        logger.info(
            "Creating external system connection -> %s of type -> %s with URL -> %s; calling -> %s",
            connection_name,
            connection_type,
            as_url,
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=external_system_post_body,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create external system connection -> %s; status -> %s; error -> %s",
                    connection_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def create_transport_workbench(self, workbench_name: str) -> dict | None:
        """Create a Workbench in the Transport Volume.

        Args:
            workbench_name (str): Name of the workbench to be created
        Returns:
            dict: Create response or None if the creation fails.
        """

        create_worbench_post_data = {"type": "528", "name": workbench_name}

        request_url = self.config()["nodesUrlv2"]
        request_header = self.request_form_header()

        logger.info(
            "Create transport workbench -> %s; calling -> %s",
            workbench_name,
            request_url,
        )
        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=create_worbench_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create transport workbench -> %s; status -> %s; error -> %s",
                    workbench_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def unpack_transport_package(
        self, package_id: int, workbench_id: int
    ) -> dict | None:
        """Unpack an existing Transport Package into an existing Workbench.

        Args:
            package_id (int): ID of package to be unpacked
            workbench_id (int): ID of target workbench
        Returns:
            dict: Unpack response or None if the unpacking fails.
        """

        unpack_package_post_data = {"workbench_id": workbench_id}

        request_url = self.config()["nodesUrlv2"] + "/" + str(package_id) + "/unpack"
        request_header = self.request_form_header()

        logger.info(
            "Unpack transport package with ID -> %s into workbench with ID -> %s; calling -> %s",
            str(package_id),
            str(workbench_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=unpack_package_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to unpack package -> %s; to workbench -> %s; status -> %s; error -> %s",
                    str(package_id),
                    str(workbench_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def deploy_workbench(self, workbench_id: int) -> dict | None:
        """Deploy an existing Workbench.

        Args:
            workbench_d (int): ID of the workbench to be deployed
        Returns:
            dict: Deploy response or None if the deployment fails.
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(workbench_id) + "/deploy"
        request_header = self.request_form_header()

        logger.info(
            "Deploy workbench with ID -> %s; calling -> %s",
            str(workbench_id),
            request_url,
        )

        retries = 0
        while True:
            # As this is a potentially long-running request we put it in try / except:
            try:
                response = requests.post(
                    url=request_url,
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
            except requests.exceptions.RequestException as exception:
                logger.error(
                    "Error deploying workbench -> %s; error -> %s",
                    str(workbench_id),
                    exception.strerror,
                )
                return None
            if response.ok:
                response_dict = self.parse_request_response(response)
                if not response_dict:
                    logger.error("Error deploying workbench -> %s", str(workbench_id))
                    return None
                return response_dict
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.warning(
                    "Failed to depoloy workbench -> %s; status -> %s; error -> %s",
                    workbench_id,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def deploy_transport(
        self,
        package_url: str,
        package_name: str,
        package_description: str = "",
        replacements: list | None = None,
        extractions: list | None = None,
    ) -> dict | None:
        """Main method to deploy a transport. This uses subfunctions to upload,
           unpackage and deploy the transport, and creates the required workbench.

        Args:
            package_url (str): URL to download the transport package.
            package_name (str): Name of the transport package ZIP file
            package_description (str): Description of the transport package
            replacements (list of dicts): List of replacement values to be applied
                                          to all XML files in transport;
                                          each dict needs to have two values:
                                          - placeholder: text to replace
                                          - value: text to replace with
            extractions (list of dicts): List of XML Subtrees to extract
                                         each XML file in transport;
                                         each dict needs to have two values:
                                          - xpath: defining the subtree to extract
                                          - enabled: True if the extraction is active
        Returns:
            dict: Deploy response or None if the deployment fails.
        """

        if replacements is None:
            replacements = []
        if extractions is None:
            extractions = []

        # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
        response = self.get_volume(525)
        transport_root_volume_id = self.get_result_value(response, "id")
        if not transport_root_volume_id:
            logger.error("Failed to retrieve transport root volume")
            return None
        logger.info("Transport root volume ID -> %s", str(transport_root_volume_id))

        response = self.get_node_by_parent_and_name(
            transport_root_volume_id, "Transport Packages"
        )
        transport_package_volume_id = self.get_result_value(response, "id")
        if not transport_package_volume_id:
            logger.error("Failed to retrieve transport package volume")
            return None
        logger.info(
            "Transport package volume ID -> %s", str(transport_package_volume_id)
        )

        # Step 1: Upload Transport Package
        logger.info("Check if transport package -> %s already exists...", package_name)
        response = self.get_node_by_parent_and_name(
            transport_package_volume_id, package_name
        )
        package_id = self.get_result_value(response, "id")
        if package_id:
            logger.info(
                "Transport package -> %s does already exist; existing package ID -> %s",
                package_name,
                str(package_id),
            )
        else:
            logger.info(
                "Transport package -> %s does not yet exist, loading from -> %s",
                package_name,
                package_url,
            )
            # If we have string replacements configured execute them now:
            if replacements:
                logger.info(
                    "Transport -> %s has replacements -> %s",
                    package_name,
                    str(replacements),
                )
                self.replace_transport_placeholders(package_url, replacements)
            else:
                logger.info("Transport -> %s has no replacements!", package_name)
            # If we have data extractions configured execute them now:
            if extractions:
                logger.info(
                    "Transport -> %s has extractions -> %s",
                    package_name,
                    str(extractions),
                )
                self.extract_transport_data(package_url, extractions)
            else:
                logger.info("Transport -> %s has no extractions!", package_name)
            # Upload package to Extended ECM:
            response = self.upload_file_to_volume(
                package_url, package_name, "application/zip", 531
            )
            package_id = self.get_result_value(response, "id")
            if not package_id:
                logger.error("Failed to upload transport package -> %s", package_url)
                return None
            logger.info(
                "Successfully uploaded transport package -> %s; new package ID -> %s",
                package_name,
                str(package_id),
            )

        # Step 2: Create Transport Workbench (if not yet exist)
        workbench_name = package_name.split(".")[0]
        logger.info("Check if workbench -> %s is already deployed...", workbench_name)
        # check if the package name has the suffix "(deployed)" - this indicates it is alreadey
        # successfully deployed (see renaming at the end of this method)
        response = self.get_node_by_parent_and_name(
            transport_root_volume_id, workbench_name + " (deployed)"
        )
        workbench_id = self.get_result_value(response, "id")
        if workbench_id:
            logger.info(
                "Workbench -> %s has already been deployed successfully; existing workbench ID -> %s; skipping transport",
                workbench_name,
                str(workbench_id),
            )
            # we return and skip this transport...
            return response
        else:
            logger.info("Check if workbench -> %s already exists...", workbench_name)
            response = self.get_node_by_parent_and_name(
                transport_root_volume_id, workbench_name
            )
            workbench_id = self.get_result_value(response, "id")
            if workbench_id:
                logger.info(
                    "Workbench -> %s does already exist but is not successfully deployed; existing workbench ID -> %s",
                    workbench_name,
                    str(workbench_id),
                )
            else:
                response = self.create_transport_workbench(workbench_name)
                workbench_id = self.get_result_value(response, "id")
                if not workbench_id:
                    logger.error("Failed to create workbench -> %s", workbench_name)
                    return None
                logger.info(
                    "Successfully created workbench -> %s; new workbench ID -> %s",
                    workbench_name,
                    str(workbench_id),
                )

        # Step 3: Unpack Transport Package to Workbench
        logger.info(
            "Unpack transport package -> %s (%s) to workbench -> %s (%s)",
            package_name,
            str(package_id),
            workbench_name,
            str(workbench_id),
        )
        response = self.unpack_transport_package(package_id, workbench_id)
        if not response:
            logger.error("Failed to unpack the transport package -> %s", package_name)
            return None
        logger.info(
            "Successfully unpackaged to workbench -> %s (%s)",
            workbench_name,
            str(workbench_id),
        )

        # Step 4: Deploy Workbench
        logger.info("Deploy workbench -> %s (%s)", workbench_name, str(workbench_id))
        response = self.deploy_workbench(workbench_id)
        if not response:
            logger.error("Failed to deploy workbench -> %s", workbench_name)
            return None

        logger.info(
            "Successfully deployed workbench -> %s (%s)",
            workbench_name,
            str(workbench_id),
        )
        self.rename_node(
            workbench_id,
            workbench_name + " (deployed)",
            package_description,
        )

        return response

    # end method definition

    def replace_transport_placeholders(
        self, zip_file_path: str, replacements: list
    ) -> bool:
        """Search and replace strings in the XML files of the transport package

        Args:
            zip_file_path (str): Path to transport zip file
            replacements (list of dicts): List of replacement values; dict needs to have two values:
                                         * placeholder: text to replace
                                         * value: text to replace with
        Returns:
            Filename to the updated zip file
        """

        if not os.path.isfile(zip_file_path):
            logger.error("Zip file -> %s not found.", zip_file_path)
            return False

        # Extract the zip file to a temporary directory
        zip_file_folder = os.path.splitext(zip_file_path)[0]
        with zipfile.ZipFile(zip_file_path, "r") as zfile:
            zfile.extractall(zip_file_folder)

        modified = False

        # Replace search pattern with replace string in all XML files in the directory and its subdirectories
        for replacement in replacements:
            if not "value" in replacement:
                logger.error(
                    "Replacement needs a value but it is not specified. Skipping..."
                )
                continue
            if "enabled" in replacement and not replacement["enabled"]:
                logger.info(
                    "Replacement for transport -> %s is disabled. Skipping...",
                    zip_file_path,
                )
                continue
            # there are two types of replacements:
            # 1. XPath - more elegant and powerful
            # 2. Search & Replace - basically treat the XML file like a text file and do a search & replace
            if "xpath" in replacement:
                logger.info(
                    "Using xpath -> %s to narrow down the replacement",
                    replacement["xpath"],
                )
                if "setting" in replacement:
                    logger.info(
                        "Looking up setting -> %s in XML element",
                        replacement["setting"],
                    )
                if "assoc_elem" in replacement:
                    logger.info(
                        "Looking up assoc element -> %s in XML element",
                        replacement["assoc_elem"],
                    )
            else:  # we have a simple "search & replace" replacement
                if not "placeholder" in replacement:
                    logger.error(
                        "Replacement without an xpath needs a placeholder value but it is not specified. Skipping..."
                    )
                    continue
                if replacement.get("placeholder") == replacement["value"]:
                    logger.info(
                        "Placeholder and replacement are identical -> %s. Skipping...",
                        replacement["value"],
                    )
                    continue
                logger.info(
                    "Replace -> %s with -> %s in Transport package -> %s",
                    replacement["placeholder"],
                    replacement["value"],
                    zip_file_folder,
                )

            found = XML.replace_in_xml_files(
                zip_file_folder,
                replacement.get("placeholder"),
                replacement["value"],
                replacement.get("xpath"),
                replacement.get("setting"),
                replacement.get("assoc_elem"),
            )
            if found:
                logger.info(
                    "Replacement -> %s has been completed successfully for Transport package -> %s",
                    replacement,
                    zip_file_folder,
                )
                modified = True
            else:
                logger.warning(
                    "Replacement -> %s not found in Transport package -> %s",
                    replacement,
                    zip_file_folder,
                )

        if not modified:
            logger.warning(
                "None of the specified replacements have been found in Transport package -> %s. No need to create a new transport package.",
                zip_file_folder,
            )
            return False

        # Create the new zip file and add all files from the directory to it
        new_zip_file_path = (
            os.path.dirname(zip_file_path) + "/new_" + os.path.basename(zip_file_path)
        )
        logger.info(
            "Content of transport -> %s has been modified - repacking to new zip file -> %s",
            zip_file_folder,
            new_zip_file_path,
        )
        with zipfile.ZipFile(new_zip_file_path, "w", zipfile.ZIP_DEFLATED) as zip_ref:
            for subdir, _, files in os.walk(
                zip_file_folder
            ):  # 2nd parameter is not used, thus using _ instead of dirs
                for file in files:
                    file_path = os.path.join(subdir, file)
                    rel_path = os.path.relpath(file_path, zip_file_folder)
                    zip_ref.write(file_path, arcname=rel_path)

        # Close the new zip file and delete the temporary directory
        zip_ref.close()
        old_zip_file_path = (
            os.path.dirname(zip_file_path) + "/old_" + os.path.basename(zip_file_path)
        )
        logger.info(
            "Rename orginal transport zip file -> %s to -> %s",
            zip_file_path,
            old_zip_file_path,
        )
        os.rename(zip_file_path, old_zip_file_path)
        logger.info(
            "Rename new transport zip file -> %s to -> %s",
            new_zip_file_path,
            zip_file_path,
        )
        os.rename(new_zip_file_path, zip_file_path)

        # Return the path to the new zip file
        return True

        # end method definition

    def extract_transport_data(self, zip_file_path: str, extractions: list) -> bool:
        """Search and extract XML data from the transport package

        Args:
            zip_file_path (str): Path to transport zip file
            extractions (list of dicts): List of extraction values; dict needs to have two values:
                                         * xpath: structure to find
                                         * enabed (optional): if the extraction is active
        Returns:
            True if successful, False otherwise. THIS METHOD MODIFIES EXTRACTIONS
            BY ADDING A NEW KEY "data" TO EACH EXTRACTION ELEMENT!!
        """

        if not os.path.isfile(zip_file_path):
            logger.error("Zip file -> %s not found.", zip_file_path)
            return False

        # Extract the zip file to a temporary directory
        zip_file_folder = os.path.splitext(zip_file_path)[0]
        with zipfile.ZipFile(zip_file_path, "r") as zfile:
            zfile.extractall(zip_file_folder)

        # Extract data from all XML files in the directory and its subdirectories
        for extraction in extractions:
            if not "xpath" in extraction:
                logger.error(
                    "Extraction needs an XPath but it is not specified. Skipping..."
                )
                continue
            if "enabled" in extraction and not extraction["enabled"]:
                logger.info(
                    "Extraction for transport -> %s is disabled. Skipping...",
                    zip_file_path,
                )
                continue

            xpath = extraction["xpath"]
            logger.info(
                "Using xpath -> %s to extract the data",
                xpath,
            )

            # This delivers a list of strings containing the extracted data:
            extracted_data = XML.extract_from_xml_files(
                zip_file_folder,
                xpath,
            )
            if extracted_data:
                logger.info(
                    "Extraction with XPath -> %s has been successfully completed for Transport package -> %s",
                    xpath,
                    zip_file_folder,
                )
                # Add the extracted elements to the extraction data structure (dict).
                extraction["data"] = extracted_data
            else:
                logger.warning(
                    "Extraction with XPath -> %s has not delivered any data for Transport package -> %s",
                    xpath,
                    zip_file_folder,
                )
                extraction["data"] = []

        # Return the path to the new zip file
        return True

        # end method definition

    def get_business_object_types(self) -> dict | None:
        """Get information for all configured business object types.

        Args:
            None
        Returns:
            dict: Workspace Types information (for all external systems)
                  or None if the request fails.
        """

        request_url = self.config()["businessObjectTypesUrl"]
        request_header = self.request_form_header()

        logger.info(
            "Get all business object types; calling -> %s",
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get business object types; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_business_object_type(
        self,
        external_system_id: str,
        type_name: str,
        expand_workspace_type: bool = True,
        expand_external_system: bool = True,
    ) -> dict | None:
        """Get business object type information. Unfortunately this REST API is
           pretty much limited. It does not return Field names of external system properties
           and also does not return property groups defined.

        Args:
            external_system_id (str): External system Id (such as "TM6")
            type_name (str): Type name of the business object (such as "SAP Customer")
        Returns:
            dict: Business Object Type information or None if the request fails.

            Example response:
            {
                'businessProperties': [
                    {
                        'attributeID': '14012_29',
                        'categoryID': '14012',
                        'name': 'Name',
                        'type': 'String'
                    },
                    {
                        'attributeID': '14012_28',
                        'categoryID': '14012',
                        'name': 'Customer Number',
                        'type': 'String'
                    }
                ]
                'bwsinfo': {'id': None},
                'cadxref_doc_info': {'has_relation': False},
                'categories': [],
                'claimed_doc_info': {'is_claimed': False},
                'columns': [{...}, {...}, {...}, {...}],
                'doctemplates_info': {'isInDocTemplateVolTree': False},
                'followups': [],
                'nicknames': {'nickname': '16568'},
                'properties': {
                    'advanced_versioning': None,
                    'container': False,
                    'container_size': 0,
                    'create_date': '2017-11-23T16:43:34Z',
                    'create_user_id': 1000,
                    'description': '',
                    'description_multilingual': {...},
                    'external_create_date': None,
                    'external_identity': '',
                    ...
                },
                'rmiconsdata': {'class_id': 0, 'official': 0, 'show_classify': False, 'show_hold': False, 'show_hold_tab': False, 'show_label_tab': True, 'show_official': False, 'show_xref': False, 'show_xref_tab': False},
                'sestatus_doc_info': {'is_se_document': False, 'sync_tooltip': ''},
                'sharing_info': {'is_shared': False, 'sync_state': -1},
                'showmainruleicon': False,
                ...
            }
        """

        query = {
            "expand_ext_system": expand_external_system,
            "expand_wksp_type": expand_workspace_type,
        }

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        encoded_type_name = type_name.replace("/", "%2F")

        request_url = (
            self.config()["externalSystemUrl"]
            + "/"
            + external_system_id
            + "/botypes/"
            + encoded_type_name
            + "?{}".format(encoded_query)
        )
        request_header = self.request_form_header()

        logger.info(
            "Get business object type -> %s for external system -> %s; calling -> %s",
            type_name,
            external_system_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get business object type -> %s; status -> %s; error -> %s",
                    type_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_business_objects(
        self,
        external_system_id: str,
        type_name: str,
        where_clauses: dict | None = None,
        limit: int | None = None,
        page: int | None = None,
    ) -> dict | None:
        """Get all business objects for an external system and a given business object type.

        Args:
            external_system_id (str): External system Id (such as "TM6")
            type_name (str): Type name of the business object (such as "SAP Customer")
            where_clause (dict, optional): filter the results based on 1 or kultiple
                                           where clauses (THE  NAME CONVENTION FOR THE
                                           FIELDS IS UNCLEAR)
            limit (int, optional): maximum result items
            page (int, optional): page for chunked result lists
        Returns:
            dict: Business Object information (for all results)
                  or None if the request fails.

            Example response (for a Salesforce Account):
            {
                'links': {'data': {...}},
                'paging': {'limit': 500, 'page': 1, 'page_total': 1, 'range_max': 15, 'range_min': 1, 'total_count': 15},
                'results': {
                    'column_descriptions': [
                        {
                            'fieldLabel': 'AccountDetail.AccountID',
                            'fieldName': 'Account.ID',
                            'keyField': 'X',
                            'length': 18,
                            'position': 4
                        },
                        {
                            'fieldLabel': 'AccountName',
                            'fieldName': 'Account.Name',
                            'keyField': ' ',
                            'length': 255,
                            'position': 2
                        },
                        {
                            'fieldLabel': 'AccountNumber',
                            'fieldName': 'Account.AccountNumber',
                            'keyField': ' ',
                            'length': 40,
                            'position': 3
                        },
                        ...
                    ]
                    'max_rows_exceeded': False,
                    'result_rows': [
                        {
                            'AccountDetail.AccountID': '001Dn00000w0bCQIAY',
                            'AccountDetail.AccountName': 'Jet Stream Inc.',
                            'AccountDetail.AccountNumber': '1234567',
                            'AccountDetail.AccountOwner': 'Nick Wheeler',
                            'AccountDetail.AnnualRevenue': '$900001',
                            'AccountDetail.Description': '',
                            'AccountDetail.Employees': '',
                            'AccountDetail.Industry': 'Biotechnology',
                            'AccountDetail.ParentAccount': '',
                            ...
                        },
                        ...
                    ]
                }
            }
        """

        query = {
            "ext_system_id": external_system_id,
            "bo_type": type_name,
        }
        if limit:
            query["limit"] = limit
        if page:
            query["page"] = page
        if where_clauses:
            query.update(
                {("where_" + key): value for key, value in where_clauses.items()}
            )

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["businessObjectsUrl"] + "?{}".format(encoded_query)
        request_header = self.request_form_header()

        logger.info(
            "Get all business objects of type -> %s from external system -> %s; calling -> %s",
            type_name,
            external_system_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get business objects of type -> %s from external system -> %s; status -> %s; error -> %s",
                    type_name,
                    external_system_id,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_business_objects_search(
        self,
        external_system_id: str,
        type_name: str,
    ) -> dict | None:
        """Get business object type information. Unfortunately this REST API is
           pretty much limited. It does not return Field names of external system properties
           and also does not return property groups defined.

        Args:
            external_system_id (str): External system Id (such as "TM6")
            type_name (str): Type name of the business object (such as "SAP Customer")
        Returns:
            dict: Business Object Search Form or None if the request fails.
        """

        query = {
            "ext_system_id": external_system_id,
            "bo_type": type_name,
        }

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["businessObjectsSearchUrl"] + "?{}".format(
            encoded_query
        )
        request_header = self.request_form_header()

        logger.info(
            "Get search form for business object type -> %s and external system -> %s; calling -> %s",
            type_name,
            external_system_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get search form for business object type -> %s and external system -> %s; status -> %s; error -> %s",
                    type_name,
                    external_system_id,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_workspace_types(
        self, expand_workspace_info: bool = True, expand_templates: bool = True
    ) -> dict | None:
        """Get all workspace types configured in Extended ECM.

        Args:
            expand_workspace_info (bool, optional): Controls if the workspace info
                                                    is returned as well
            expand_workspace_info (bool, optional): Controls if the list of workspace templates
                                                    per workspace typ is returned as well
        Returns:
            dict: Workspace Types or None if the request fails.

            Example response:
            {
                'links': {
                    'data': {...}
                },
                'results': [
                    {
                        'data': {
                            'properties': {
                                'rm_enabled': False,
                                'templates': [
                                    {
                                        'id': 14471,
                                        'name': 'Campaign',
                                        'subtype': 848
                                    },
                                    ...
                                ],
                                'wksp_type_id': 35,
                                'wksp_type_name': 'Campaign'
                            },
                            'wksp_info': {
                                'wksp_type_icon': '/appimg/ot_bws/icons/13147%2Esvg?v=161108_84584'
                            }
                        }
                    }
                ]
            }
        """

        request_url = self.config()["businessWorkspaceTypesUrl"]
        if expand_templates:
            request_url += "?expand_templates=true"
        else:
            request_url += "?expand_templates=false"
        if expand_workspace_info:
            request_url += "&expand_wksp_info=true"
        else:
            request_url += "&expand_wksp_info=false"

        request_header = self.request_form_header()

        logger.info("Get workspace types; calling -> %s", request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get workspace types; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_workspace_create_form(
        self,
        template_id: int,
        external_system_id: int = None,
        bo_type: int = None,
        bo_id: int = None,
        parent_id: int = None,
    ) -> dict | None:
        """Get the Workspace create form.

        Args:
            template_id (int): ID of the workspace template
            external_system_id (int, optional): Identifier of the external system (None if no external system)
            bo_type (int, optional): Business object type (None if no external system)
            bo_id (int, optional): Business object identifier / key (None if no external system)
            parent_id (int, optional): Parent ID of the workspaces. Needs only be specified in special
                                       cases where workspace location cannot be derived from workspace
                                       type definition, e.g. sub-workspace
        Returns:
            dict: Workspace Create Form data or None if the request fails.
        """

        request_url = self.config()[
            "businessworkspacecreateform"
        ] + "?template_id={}".format(template_id)
        # Is a parent ID specifified? Then we need to add it to the request URL
        if parent_id is not None:
            request_url += "&parent_id={}".format(parent_id)
        # Is this workspace connected to a business application / external system?
        if external_system_id and bo_type and bo_id:
            request_url += "&ext_system_id={}".format(external_system_id)
            request_url += "&bo_type={}".format(bo_type)
            request_url += "&bo_id={}".format(bo_id)
            logger.info(
                "Include business object connection -> (%s, %s, %s) in workspace create form...",
                str(external_system_id),
                str(bo_type),
                str(bo_id),
            )
        request_header = self.request_form_header()

        logger.info(
            "Get workspace create form for workspace template ID -> %s; calling -> %s",
            str(template_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get workspace create form for template -> %s; status -> %s; error -> %s",
                    str(template_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_workspace(self, node_id: int) -> dict | None:
        """Get a workspace based on the node ID.

        Args:
            node_id (int): Node ID of the workspace to retrieve.
        Returns:
            dict: Workspace node information or None if no node with this ID is found.

            Example response:
            {
                'links': {
                    'data': {...}
                },
                'meta_data': {
                    'properties': {...}
                },
                'paging': {
                    'limit': 500,
                    'page': 1,
                    'page_total': 1,
                    'range_max': 1,
                    'range_min': 1,
                    'total_count': 1
                },
                'results': [
                    {
                        'actions': {...},
                        'data': {
                            'business_properties': {
                                'business_object_id': '000004000240',
                                'business_object_type': 'BUS2007',
                                'business_object_type_id': 18,
                                'business_object_type_name': 'Maintenance Order',
                                'business_object_type_name_multilingual': {...},
                                'display_url': "https://fiori.qa.idea-te.eimdemo.com:8443/sap/bc/ui2/flp#MaintenanceOrder-displayXecmFactSheet&//C_ObjPgMaintOrder('000004000240')",
                                'external_system_id': 'TM6',
                                'external_system_name': 'TM6',
                                'has_default_display': True,
                                'has_default_search': True,
                                'isEarly': False,
                                'workspace_type_id': 42,
                                'workspace_type_name': 'Maintenance Order',
                                'workspace_type_name_multilingual': {},
                                ...
                            }
                            'properties': {
                                'volume_id': -2000,
                                'id': 36780,
                                'parent_id': 13567,
                                'owner_user_id': 7240,
                                'name': '4600000044 - C.E.B. New York Inc.',
                                'type': 848,
                                'description': '',
                                'create_date': '2023-09-02T11:07:06',
                                'create_user_id': 7240,
                                'create_user_id': 7240,
                                'modify_date': '2023-09-02T11:07:11',
                                'modify_user_id': 7240,
                                'reserved': False,
                                'reserved_user_id': 0,
                                'reserved_date': None,
                                'order': None,
                                'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                                'hidden': False,
                                'mime_type': None,
                                'original_id': 0,
                                'wnf_wksp_type_id': 16,
                                'wnf_wksp_template_id': 15615,
                                'size_formatted': '7 Items',
                                'type_name': 'Business Workspace',
                                'container': True,
                                'size': 7,
                                ...
                            }
                            'wksp_info':
                            {
                                'wksp_type_icon': '/appimg/ot_bws/icons/16634%2Esvg?v=161194_13949'
                            }
                        },
                        'metadata': {...},
                        'metadata_order': {...}
                    }
                ],
                'wksp_info': {
                    'wksp_type_icon': None
                }
                'workspace_references': [
                    {
                        'business_object_id': '000004000240',
                        'business_object_type': 'BUS2007',
                        'business_object_type_id': 18,
                        'external_system_id': 'TM6',
                        'has_default_display': True,
                        'has_default_search': True,
                        'workspace_type_id': 42
                    }
                ]
            }
        """

        request_url = self.config()["businessWorkspacesUrl"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.info(
            "Get workspace with ID -> %s; calling -> %s", str(node_id), request_url
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get workspace with ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_workspace_instances(
        self, type_name: str = "", type_id: int = None, expanded_view: bool = True
    ):
        """Get all workspace instances of a given type. This is a convenience
           wrapper method for get_workspace_by_type_and_name()

        Args:
            type_name (str, optional): Name of the workspace type
            type_id (int, optional): ID of the workspace_type
            expanded_view (bool, optional): If 'False' then just search in recently
                                            accessed business workspace for this name and type.
                                            If 'True' (this is the default) then search in all
                                            workspaces for this name and type.
        Returns:
            dict: Workspace information or None if the workspace is not found.
        """

        # Omitting the name lets it return all instances of the type:
        return self.get_workspace_by_type_and_name(
            type_name=type_name, type_id=type_id, name="", expanded_view=expanded_view
        )

    # end method definition

    def get_workspace_by_type_and_name(
        self,
        type_name: str = "",
        type_id: int = None,
        name: str = "",
        expanded_view: bool = True,
    ) -> dict | None:
        """Lookup workspace based on workspace type and workspace name.

        Args:
            type_name (str, optional): name of the workspace type
            type_id (int, optional): ID of the workspace_type
            name (str, optional): Name of the workspace, if "" then deliver all instances
                                  of the given workspace type.
            expanded_view (bool, optional): If 'False' then just search in recently
                                            accessed business workspace for this name and type.
                                            If 'True' (this is the default) then search in all
                                            workspaces for this name and type.
        Returns:
            dict: Workspace information or None if the workspace is not found.
        """

        # Add query parameters (these are NOT passed via JSon body!)
        query = {
            "expanded_view": expanded_view,
        }
        if type_name:
            query["where_workspace_type_name"] = type_name
        if type_id:
            query["where_workspace_type_id"] = type_id
        if name:
            query["where_name"] = name

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["businessWorkspacesUrl"] + "?{}".format(
            encoded_query
        )
        request_header = self.request_form_header()

        if name:
            logger.info(
                "Get workspace with name -> %s and type -> %s; calling -> %s",
                name,
                type_name,
                request_url,
            )
        else:
            logger.info(
                "Get all workspace instances of type -> %s; calling -> %s",
                type_name,
                request_url,
            )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if name:
                    logger.warning(
                        "Failed to get workspace -> %s of type -> %s; status -> %s; error -> %s",
                        name,
                        type_name,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.warning(
                        "Failed to get workspace instances of type -> %s; status -> %s; error -> %s",
                        type_name,
                        response.status_code,
                        response.text,
                    )
                return None

    # end method definition

    def get_workspace_by_business_object(
        self,
        external_system_name: str,
        business_object_type: str,
        business_object_id: str,
        return_workspace_metadata: bool = False,
        show_error: bool = False,
    ) -> dict | None:
        """Get a workspace based on the business object of an external system.

        Args:
            external_system_name (str): Name of the connection
            business_object_type (str): Type of the Business object, e.g. KNA1 for SAP customers
            business_object_id (str): ID of the business object in the external system
            return_workspace_metadata (bool, optional): Whether or not workspace metadata (categories) should be returned.
                                                        Default is False.
            show_error (bool, optional): Treat as error if node is not found. Default is False.
        Returns:
            dict: Workspace node information or None if no node with this ID is found.

            Example response:
            {
                'links': {
                    'data': {...}
                },
                'meta_data': {
                    'properties': {...}
                },
                'paging': {
                    'limit': 500,
                    'page': 1,
                    'page_total': 1,
                    'range_max': 1,
                    'range_min': 1,
                    'total_count': 1
                },
                'results': [
                    {
                        'actions': {...},
                        'data': {
                            'properties': {
                                'volume_id': -2000,
                                'id': 36780,
                                'parent_id': 13567,
                                'owner_user_id': 7240,
                                'name': '4600000044 - C.E.B. New York Inc.',
                                'type': 848,
                                'description': '',
                                'create_date': '2023-09-02T11:07:06',
                                'create_user_id': 7240,
                                'create_user_id': 7240,
                                'modify_date': '2023-09-02T11:07:11',
                                'modify_user_id': 7240,
                                'reserved': False,
                                'reserved_user_id': 0,
                                'reserved_date': None,
                                'order': None,
                                'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                                'hidden': False,
                                'mime_type': None,
                                'original_id': 0,
                                'wnf_wksp_type_id': 16,
                                'wnf_wksp_template_id': 15615,
                                'size_formatted': '7 Items',
                                'type_name': 'Business Workspace',
                                'container': True,
                                'size': 7,
                                ...
                            }
                        },
                        'metadata': {...},
                        'metadata_order': {...}
                    }
                ],
                'wksp_info': {
                    'wksp_type_icon': None
                }
            }
        """

        request_url = (
            self.config()["externalSystemUrl"]
            + "/"
            + external_system_name
            + "/botypes/"
            + business_object_type
            + "/boids/"
            + business_object_id
        )
        if return_workspace_metadata:
            request_url += "?metadata"

        request_header = self.request_form_header()

        logger.info(
            "Get workspace via external system -> %s (Business Object Type -> %s; Business Object ID -> %s); calling -> %s",
            external_system_name,
            business_object_type,
            business_object_id,
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to get workspace via external system -> %s (Business Object Type -> %s; Business Object ID -> %s); status -> %s; error -> %s",
                        external_system_name,
                        business_object_type,
                        business_object_id,
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.info(
                        "Cannot fing workspace via external system -> %s (Business Object Type -> %s; Business Object ID -> %s); status -> %s; error -> %s",
                        external_system_name,
                        business_object_type,
                        business_object_id,
                        response.status_code,
                        response.text,
                    )
                return None

    # end method definition

    def create_workspace(
        self,
        workspace_template_id: int,
        workspace_name: str,
        workspace_description: str,
        workspace_type: int,
        category_data: dict | None = None,
        external_system_id: int = None,
        bo_type: int | None = None,
        bo_id: int | None = None,
        parent_id: int | None = None,
        ibo_workspace_id: int | None = None,
        show_error: bool = True,
    ) -> dict | None:
        """Create a new business workspace.

        Args:
            workspace_template_id (int): ID of the workspace template
            workspace_name (str): Name of the workspace
            workspace_description (str): Description of the workspace
            workspace_type (int): Type ID of the workspace
            category_data (dict): Category and attributes
            external_system_id (str, optional): Identifier of the external system (None if no external system)
            bo_type (str, optional): Business object type (None if no external system)
            bo_id (str, optional): Business object identifier / key (None if no external system)
            parent_id (str, optional): Parent ID of the workspaces. Needs only be specified in special
                                       cases where workspace location cannot be derived from workspace
                                       type definition
            ibo_workspace_id (int, optional): Node ID of an existing workspace that is already connected to another
                                              external system. This allows for subsequent calls to coonect the workspace
                                              to multiple Business Objects (IBO = Identical Business Objects)
            show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
        Returns:
            dict: Workspace Create Form data or None if the request fails.
        """

        # Avoid linter warning W0102
        if category_data is None:
            category_data = {}

        create_workspace_post_data = {
            "template_id": str(workspace_template_id),
            "name": workspace_name,
            "description": workspace_description,
            "wksp_type_id": str(workspace_type),
            "type": str(848),
            "roles": category_data,
        }

        # Is this workspace connected to a business application / external system?
        if external_system_id and bo_type and bo_id:
            create_workspace_post_data["ext_system_id"] = str(external_system_id)
            create_workspace_post_data["bo_type"] = str(bo_type)
            create_workspace_post_data["bo_id"] = str(bo_id)
            logger.info(
                "Use business object connection -> (%s, %s, %s) for workspace -> %s",
                str(external_system_id),
                str(bo_type),
                str(bo_id),
                workspace_name,
            )
            if ibo_workspace_id:
                logger.info(
                    "This is a subsequent call to create a cross-application workspace (IBO)"
                )
                create_workspace_post_data["ibo_workspace_id"] = ibo_workspace_id

        # If workspace creation location cannot be derived from the workspace type
        # there may be an optional parent parameter passed to this method. This can
        # also be the case if workspaces are nested into each other:
        if parent_id is not None:
            create_workspace_post_data["parent_id"] = parent_id
            logger.info(
                "Use specified location -> %s for workspace -> %s",
                str(parent_id),
                workspace_name,
            )
        else:
            logger.info(
                "Determine location of workspace -> %s via workspace type -> %s",
                workspace_name,
                str(workspace_type),
            )

        request_url = self.config()["businessWorkspacesUrl"]
        request_header = self.request_form_header()

        logger.info(
            "Create workspace -> %s with type -> %s from template -> %s; calling -> %s",
            workspace_name,
            str(workspace_type),
            str(workspace_template_id),
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            # See https://developer.opentext.com/apis/14ba85a7-4693-48d3-8c93-9214c663edd2/4403207c-40f1-476a-b794-fdb563e37e1f/07229613-7ef4-4519-8b8a-47eaff639d42#operation/createBusinessWorkspace
            response = requests.post(
                url=request_url,
                headers=request_header,
                data={"body": json.dumps(create_workspace_post_data)},
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if show_error:
                    logger.error(
                        "Failed to create workspace -> %s from template with ID -> %s; status -> %s; error -> %s",
                        workspace_name,
                        str(workspace_template_id),
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.warning(
                        "Couldn't create workspace -> %s from template with ID -> %s (it may exist already); status -> %s; error -> %s",
                        workspace_name,
                        str(workspace_template_id),
                        response.status_code,
                        response.text,
                    )
                return None

    # end method definition

    def create_workspace_relationship(
        self,
        workspace_id: int,
        related_workspace_id: int,
        relationship_type: str = "child",
    ) -> dict | None:
        """Create a relationship between two workspaces.

        Args:
            workspace_id (int): ID of the workspace
            related_workspace_id (int): ID of the related workspace
            relationship_type (str, optional): "parent" or "child" - "child" is default if omitted
        Returns:
            dict: Workspace Relationship data (json) or None if the request fails.
        """

        create_workspace_relationship_post_data = {
            "rel_bw_id": str(related_workspace_id),
            "rel_type": relationship_type,
        }

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/relateditems".format(workspace_id)
        request_header = self.request_form_header()

        logger.info(
            "Create workspace relationship between -> %s and -> %s; calling -> %s",
            str(workspace_id),
            str(related_workspace_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=create_workspace_relationship_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create workspace relationship between -> %s and -> %s; status -> %s; error -> %s",
                    str(workspace_id),
                    str(related_workspace_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_workspace_relationships(self, workspace_id: int) -> dict | None:
        """Get the Workspace relationships to other workspaces.

        Args:
            workspace_id (int): ID of the workspace template
        Returns:
            dict: Workspace relationships or None if the request fails.
        """

        request_url = (
            self.config()["businessWorkspacesUrl"]
            + "/"
            + str(workspace_id)
            + "/relateditems"
        )
        request_header = self.request_form_header()

        logger.info(
            "Get related workspaces for workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get related workspaces of workspace with ID -> %s; status -> %s; error -> %s",
                    str(workspace_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_workspace_roles(self, workspace_id: int) -> dict | None:
        """Get the Workspace roles.

        Args:
            workspace_id (int): ID of the workspace template
        Returns:
            dict: Workspace Roles data or None if the request fails.
        """

        request_url = (
            self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/roles"
        )
        request_header = self.request_form_header()

        logger.info(
            "Get workspace roles of workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get roles of workspace with ID -> %s; status -> %s; error -> %s",
                    str(workspace_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def add_member_to_workspace(
        self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
    ) -> dict | None:
        """Add member to a workspace role. Check that the user/group is not yet a member.

        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            member_id (int): User ID or Group ID
            show_warning (bool, optional): If True logs a warning if member is already in role
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        add_member_to_workspace_post_data = {"id": str(member_id)}

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/roles/{}/members".format(workspace_id, role_id)
        request_header = self.request_form_header()

        logger.info(
            "Check if user/group with ID -> %s is already in role with ID -> %s of workspace with ID -> %s; calling -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            request_url,
        )

        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if not response.ok:
            logger.error(
                "Failed to get workspace members; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

        workspace_members = self.parse_request_response(response)

        if self.exist_result_item(workspace_members, "id", member_id):
            if show_warning:
                logger.warning(
                    "User/group with ID -> %s is already a member of role with ID -> %s of workspace with ID -> %s",
                    str(member_id),
                    str(role_id),
                    str(workspace_id),
                )
            return workspace_members

        logger.info(
            "Add user/group with ID -> %s to role with ID -> %s of workspace with ID -> %s; calling -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            request_url,
        )

        response = requests.post(
            url=request_url,
            headers=request_header,
            data=add_member_to_workspace_post_data,
            cookies=self.cookie(),
            timeout=None,
        )

        if response.ok:
            return self.parse_request_response(response)
        else:
            logger.error(
                "Failed to add user/group with ID -> %s to role with ID -> %s of workspace with ID -> %s; status -> %s; error -> %s",
                str(member_id),
                str(role_id),
                str(workspace_id),
                response.status_code,
                response.text,
            )
            return None

    # end method definition

    def remove_member_from_workspace(
        self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
    ) -> dict | None:
        """Remove a member from a workspace role. Check that the user is currently a member.

        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            member_id (int): User or Group Id
            show_warning (bool, optional): If True logs a warning if member is not in role
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/roles/{}/members".format(workspace_id, role_id)
        request_header = self.request_form_header()

        logger.info(
            "Check if user/group with ID -> %s is in role with ID -> %s of workspace with ID -> %s; calling -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            request_url,
        )

        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if not response.ok:
            logger.error(
                "Failed to get workspace members; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

        workspace_members = self.parse_request_response(response)

        if not self.exist_result_item(workspace_members, "id", member_id):
            if show_warning:
                logger.warning(
                    "User/group with ID -> %s is not a member of role with ID -> %s of workspace with ID -> %s",
                    str(member_id),
                    str(role_id),
                    str(workspace_id),
                )
            return None

        request_url = self.config()[
            "businessWorkspacesUrl"
        ] + "/{}/roles/{}/members/{}".format(workspace_id, role_id, member_id)

        logger.info(
            "Removing user/group with ID -> %s from role with ID -> %s of workspace with ID -> %s; calling -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            request_url,
        )

        response = requests.delete(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )

        if response.ok:
            return self.parse_request_response(response)
        else:
            logger.error(
                "Failed to remove user/group with ID -> %s from role with ID -> %s of workspace with ID -> %s; status -> %s; error -> %s",
                str(member_id),
                str(role_id),
                str(workspace_id),
                response.status_code,
                response.text,
            )
            return None

    # end method definition

    def assign_workspace_permissions(
        self, workspace_id: int, role_id: int, permissions: list, apply_to: int = 2
    ) -> dict | None:
        """Update permissions of a workspace role
        Args:
            workspace_id (int): ID of the workspace
            role_id (int): ID of the role
            permissions (list): List of permissions - potential elements:
                                "see"
                                "see_contents"
                                "modify"
                                "edit_attributes"
                                "add_items"
                                "reserve"
                                "add_major_version"
                                "delete_versions"
                                "delete"
                                "edit_permissions"
            apply_to (int, optional):  Items to apply the permission change. Possible values:
                                       0 = this item
                                       1 = sub-items
                                       2 = This item and sub-items (default)
                                       3 = This item and immediate sub-items
        Returns:
            dict: Workspace Role Membership or None if the request fails.
        """

        request_url = self.config()["businessWorkspacesUrl"] + "/{}/roles/{}".format(
            workspace_id, role_id
        )

        request_header = self.request_form_header()

        logger.info(
            "Updating Permissions of role with ID -> %s of workspace with ID -> %s with permissions -> %s; calling -> %s",
            str(role_id),
            str(workspace_id),
            str(permissions),
            request_url,
        )

        permission_post_data = {
            "permissions": permissions,
            "apply_to": apply_to,
        }

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                headers=request_header,
                data={"body": json.dumps(permission_post_data)},
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update permissions for role with ID -> %s of workspace with ID -> %s; status -> %s; error -> %s",
                    str(role_id),
                    str(workspace_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def update_workspace_icon(
        self, workspace_id: int, file_path: str, file_mimetype: str = "image/*"
    ) -> dict | None:
        """Update a workspace with a with a new icon (which is uploaded).

        Args:
            workspace_id (int): ID of the workspace
            file_path (str): path + filename of icon file
            file_mimetype (str, optional): mimetype of the image
        Returns:
            dict: Node information or None if REST call fails.
        """

        if not os.path.exists(file_path):
            logger.error("Workspace icon file does not exist -> %s", file_path)
            return None

        update_workspace_icon_post_body = {
            "file_content_type": file_mimetype,
            "file_filename": os.path.basename(file_path),
        }

        upload_workspace_icon_post_files = [
            (
                "file",
                (
                    f"{os.path.basename(file_path)}",
                    open(file_path, "rb"),
                    file_mimetype,
                ),
            )
        ]

        request_url = (
            self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/icons"
        )

        request_header = self.cookie()

        logger.info(
            "Update icon for workspace ID -> %s with icon file -> %s; calling -> %s",
            str(workspace_id),
            file_path,
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=update_workspace_icon_post_body,
                files=upload_workspace_icon_post_files,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update workspace ID -> %s with new icon -> %s; status -> %s; error -> %s",
                    str(workspace_id),
                    file_path,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_unique_names(self, names: list, subtype: int | None = None) -> dict | None:
        """Get definition information for Unique Names.

        Args:
            names (list): list of unique names to lookup.
            subtype (int): filter unique names for those pointing to a specific subtype

        Returns:
            dict | None: Unique name definition information or None if REST call fails.

            Example response:
            {
                'links': {'data': {...}},
                'results': [
                    {
                        'NodeId': 13653,
                        'NodeName': 'Functional Location',
                        'UniqueName': 'ot_templ_func_location'
                    },
                    {
                        'NodeId': 2424,
                        'NodeName': 'Content Server Document Templates',
                        'UniqueName': 'Document Templates'
                    }
                ]
            }
        """

        if not names:
            logger.error("Missing Unique Names!")
            return None

        # Add query parameters (these are NOT passed via JSon body!)
        query = {"where_names": "{" + ", ".join(names) + "}"}
        if subtype:
            query["where_subtype"] = subtype

        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["uniqueNamesUrl"] + "?{}".format(encoded_query)
        request_header = self.request_form_header()

        if subtype:
            logger.info(
                "Get unique names -> %s with subtype -> %s; calling -> %s",
                str(names),
                str(subtype),
                request_url,
            )
        else:
            logger.info(
                "Get unique names -> %s; calling -> %s",
                str(names),
                request_url,
            )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                if subtype:
                    logger.warning(
                        "Failed to get unique names -> %s of subtype -> %s; status -> %s; error -> %s",
                        str(names),
                        str(subtype),
                        response.status_code,
                        response.text,
                    )
                else:
                    logger.warning(
                        "Failed to get unique names -> %s; status -> %s; error -> %s",
                        str(names),
                        response.status_code,
                        response.text,
                    )
                return None

    def create_item(
        self,
        parent_id: int,
        item_type: str,
        item_name: str,
        item_description: str = "",
        url: str = "",
        original_id: int = 0,
    ) -> dict | None:
        """Create an Extended ECM item. This REST call is somewhat limited. It cannot set favortie (featured item) or hidden item.
           It does also not accept owner group information.

        Args:
            parent_id (int): Node ID of the parent
            item_type (str): Type of the item (e.g. 0 = foler, 140 = URL)
            item_name (str): Name of the item
            item_description (str, optional): Description of the item
            url (str, optional): Address of the URL item (if it is an URL item type)
            original_id (int, optional): Node ID of the original (referenced) item.
                                         Required if a shortcut item is created
        Returns:
            dict: Request response of the create item call or None if the REST call has failed.
        """

        create_item_post_data = {
            "parent_id": parent_id,
            "type": item_type,
            "name": item_name,
            "description": item_description,
        }

        if url:
            create_item_post_data["url"] = url
        if original_id > 0:
            create_item_post_data["original_id"] = original_id

        request_url = self.config()["nodesUrlv2"]
        request_header = self.request_form_header()

        logger.info(
            "Create item -> %s (type -> %s) under parent with ID -> %s; calling -> %s",
            item_name,
            item_type,
            str(parent_id),
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.post(
                url=request_url,
                data={"body": json.dumps(create_item_post_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create item -> %s; status -> %s; error -> %s",
                    item_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def update_item(
        self,
        node_id: int,
        parent_id: int = 0,
        item_name: str = "",
        item_description: str = "",
    ) -> dict | None:
        """Update an Extended ECM item (parent, name, description). Changing the parent ID is
           a move operation. If parent ID = 0 the item will not be moved.

        Args:
            node_id (int): ID of the node
            parent_id (int, optional): node ID of the new parent (in case of a move operation)
            item_name (str, optional): new name of the item
            item_description (str, optional): new description of the item
        Returns:
            dict: Response of the update item request or None if the REST call has failed.
        """

        update_item_put_data = {}

        if item_name:
            # this is a rename operation
            update_item_put_data["name"] = item_name
        if item_description:
            # this is a change description operation
            update_item_put_data["description"] = item_description
        if parent_id:
            # this is a move operation
            update_item_put_data["parent_id"] = parent_id

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
        request_header = self.request_form_header()

        logger.info(
            "Update item -> %s with data -> %s; calling -> %s",
            item_name,
            str(update_item_put_data),
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.put(
                url=request_url,
                data={"body": json.dumps(update_item_put_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update item -> %s; status -> %s; error -> %s",
                    item_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_document_templates(self, parent_id: int):
        """Get all document templates for a given target location.

        Args:
            parent_id (int): node ID of target location (e.g. a folder)

        Returns:
            dict: response of the REST call (converted to a Python dictionary)

            Example response:
            'results': [
                {
                    'container': False,
                    'hasTemplates': False,
                    'name': 'Document',
                    'subtype': 144,
                    'templates': [
                        {
                            'description_multilingual': {...},
                            'id': 16817,
                            'isDPWizardAvailable': False,
                            'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                            'name': 'Innovate Procurement Contract Template 2022.docx',
                            'name_multilingual': {...},
                            'size': 144365,
                            'sizeformatted': '141 KB',
                            'type': 144
                        },
                        {
                            ...
                        }
                    ]
                }
            ]
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(parent_id)
            + "/doctemplates?subtypes={144}&sidepanel_subtypes={144}"
        )
        request_header = self.request_form_header()

        logger.info(
            "Get document templates for target location -> %s (parent ID); calling -> %s",
            str(parent_id),
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get document templates for parent folder -> %s; status -> %s; error -> %s",
                    str(parent_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def create_document_from_template(
        self,
        template_id: int,
        parent_id: int,
        classification_id: int,
        category_data: dict,
        doc_name: str,
        doc_desciption: str = "",
    ) -> dict | None:
        """Create a document based on a document template

        Args:
            template_id (int): node ID of the document template
            parent_id (int): node ID of the target location (parent)
            classification_id (int): node ID of the classification
            category_data (dict): metadata / category data
                                    Example: category ID = 12508
                                    {
                                        "12508": {
                                            "12508_2": "Draft",         # Text drop-down
                                            "12508_3": 8559,            # user ID
                                            "12508_4": "2023-05-10",    # date
                                            "12508_6": 7357,            # user ID
                                            "12508_7": "2023-05-11",    # date
                                            "12508_5": True,            # checkbox / bool
                                            "12508_8": "EN",            # text drop-down
                                            "12508_9": "MS Word",       # text drop-down
                                        }
                                    }
            doc_name (str): Name of the item to create.
            doc_description (str, optional): Description of the item to create.
        """

        create_document_post_data = {
            "template_id": template_id,
            "parent_id": parent_id,
            "name": doc_name,
            "description": doc_desciption,
            "type": 144,
            "roles": {
                "categories": category_data,
                "classifications": {"create_id": [classification_id], "id": []},
            },
        }

        request_url = self.config()["doctemplatesUrl"]
        request_header = self.request_form_header()

        logger.info(
            "Create document -> %s from template with ID -> %s in target location -> %s (parent ID) with classification ID -> %s; calling -> %s",
            doc_name,
            str(template_id),
            str(parent_id),
            str(classification_id),
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            response = requests.post(
                url=request_url,
                # this seems to only work with a "body" tag and is different form the documentation
                # on developer.opentext.com
                data={"body": json.dumps(create_document_post_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create document -> %s; status -> %s; error -> %s",
                    doc_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_web_report_parameters(self, nickname: str):
        """Get parameters of a Web Report in Extended ECM. These are defined on the Web Report node
            (Properties --> Parameters)

        Args:
            nickname (str): Nickname of the Web Reports node.
        Returns:
            Response: List of Web Report parameters. Each list item is a dict describing the parameter.
            Structure of the list items:
            {
                "type": "string",
                "parm_name": "string",
                "display_text": "string",
                "prompt": true,
                "prompt_order": 0,
                "default_value": null,
                "description": "string",
                "mandatory": true
            }
            None if the REST call has failed.
        """

        request_url = self.config()["webReportsUrl"] + "/" + nickname + "/parameters"
        request_header = self.request_form_header()

        logger.info(
            "Retrieving parameters of Web Report with nickname -> %s; calling -> %s",
            nickname,
            request_url,
        )
        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                # Return the "data" element which is a list of dict items:
                result_dict = self.parse_request_response(response)
                logger.debug("Web Report parameters result -> %s", str(result_dict))
                if not result_dict.get("data"):
                    return None
                return result_dict["data"]
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to retrieve parameters of Web Report with nickname -> %s; status -> %s; error -> %s",
                    nickname,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def run_web_report(
        self, nickname: str, web_report_parameters: dict | None = None
    ) -> dict | None:
        """Run a Web Report that is identified by its nick name.

        Args:
            nickname (str): nickname of the Web Reports node.
            web_report_parameters (dict): Parameters of the Web Report (names + value pairs)
        Returns:
            dict: Response of the run Web Report request or None if the Web Report execution has failed.
        """

        # Avoid linter warning W0102:
        if web_report_parameters is None:
            web_report_parameters = {}

        request_url = self.config()["webReportsUrl"] + "/" + nickname
        request_header = self.request_form_header()

        logger.info(
            "Running Web Report with nickname -> %s; calling -> %s",
            nickname,
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=web_report_parameters,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to run web report with nickname -> %s; status -> %s; error -> %s",
                    nickname,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def install_cs_application(self, application_name: str) -> dict | None:
        """Install a CS Application (based on WebReports)

        Args:
            application_name (str): name of the application (e.g. OTPOReports, OTRMReports, OTRMSecReports)
        Returns:
            dict: Response or None if the installation of the CS Application has failed.
        """

        install_cs_application_post_data = {"appName": application_name}

        request_url = self.config()["csApplicationsUrl"] + "/install"
        request_header = self.request_form_header()

        logger.info(
            "Install CS Application -> %s; calling -> %s", application_name, request_url
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=install_cs_application_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to install CS Application -> %s; status -> %s; error -> %s",
                    application_name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def assign_item_to_user_group(
        self, node_id: int, subject: str, instruction: str, assignees: list
    ) -> dict | None:
        """Assign an Extended ECM item to users and groups. This is a function used by
           Extended ECM for Government.

        Args:
            node_id (int): node ID of the Extended ECM item (e.g. a workspace or a document)
            subject (str): title / subject of the assignment
            instructions (str): more detailed description or instructions for the assignment
            assignees (list): list of IDs of users or groups
        Returns:
            dict: Response of the request or None if the assignment has failed.
        """

        assignment_post_data = {
            "subject": subject,
            "instruction": instruction,
            "assignees": assignees,
        }

        request_url = (
            self.config()["nodesUrlv2"] + "/" + str(node_id) + "/xgovassignments"
        )

        request_header = self.request_form_header()

        logger.info(
            "Assign item with ID -> %s to assignees -> %s (subject -> %s); calling -> %s",
            str(node_id),
            str(assignees),
            subject,
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "add_assignment" tag.
            response = requests.post(
                url=request_url,
                data={"add_assignment": json.dumps(assignment_post_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign item with ID -> %s to assignees -> %s (subject -> %s); status -> %s; error -> %s",
                    str(node_id),
                    str(assignees),
                    subject,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def convert_permission_string_to_permission_value(self, permissions: list) -> int:
        """Converts a list of permission names (strongs) to a bit-mask.

        Args:
            permissions (list): List of permission names - see conversion variable below.
        Returns:
            int: bit-encoded permission value
        """

        conversion = {
            "see": 130,  # Bits 2 and 8
            "see_contents": 36865,  # Bit 17
            "modify": 65536,  # Bit 18
            "edit_attributes": 131072,  # Bit 19
            "add_items": 4,  # Bit 3
            "reserve": 8192,  # Bit 14
            "add_major_version": 4194304,  # Bit 23
            "delete_versions": 16384,  # Bit 15
            "delete": 8,  # Bit 4
            "edit_permissions": 16,  # Bit 5
        }

        permission_value = 0

        for permission in permissions:
            if not conversion.get(permission):
                logger.error("Illegal permission value -> %s", str(permission))
                return 0
            permission_value += conversion[permission]

        return permission_value

    # end method definition

    def convert_permission_value_to_permission_string(
        self, permission_value: int
    ) -> list:
        """Converts a bit-encoded permission value to a list of permission names (strings).

        Args:
            permission_value (int): bit-encoded permission value
        Returns:
            list: list of permission names
        """

        conversion = {
            "see": 130,  # Bits 2 and 8
            "see_contents": 36865,  # Bit 17
            "modify": 65536,  # Bit 18
            "edit_attributes": 131072,  # Bit 19
            "add_items": 4,  # Bit 3
            "reserve": 8192,  # Bit 14
            "add_major_version": 4194304,  # Bit 23
            "delete_versions": 16384,  # Bit 15
            "delete": 8,  # Bit 4
            "edit_permissions": 16,  # Bit 5
        }

        permissions = []

        for key, value in conversion.items():
            if permission_value & value:  # binary and
                permissions.append(key)

        return permissions

    # end method definition

    def assign_permission(
        self,
        node_id: int,
        assignee_type: str,
        assignee: int,
        permissions: list,
        apply_to: int = 0,
    ) -> dict | None:
        """Assign permissions for Extended ECM item to a user or group.

        Args:
            node_id (int): node ID of the Extended ECM item
            assignee_type (str): this can be either "owner", "group" (for owner group),
                                    "public", or "custom" (assigned access)
            assignee (int): ID of user or group ("right ID"). If 0 and assigneeType
                                is "owner" or "group" then it is assumed that the owner and
                                owner group should not be changed.
            permissions (list): list of permissions - potential elements:
                                "see"
                                "see_contents"
                                "modify"
                                "edit_attributes"
                                "add_items"
                                "reserve"
                                "add_major_version"
                                "delete_versions"
                                "delete"
                                "edit_permissions"
            apply_to (int, optional): elements to apply permissions to - potential values:
                                 0 = this item (default)
                                 1 = sub-items
                                 2 = This item and sub-items
                                 3 = This item and immediate sub-items
        Returns:
            dict: Response of the request or None if the assignment of permissions has failed.
        """

        if not assignee_type or not assignee_type in [
            "owner",
            "group",
            "public",
            "custom",
        ]:
            logger.error(
                "Missing or wrong assignee type. Needs to be owner, group, public or custom!"
            )
            return None
        if assignee_type == "custom" and not assignee:
            logger.error("Missing permission assignee!")
            return None

        permission_post_data = {
            "permissions": permissions,
            "apply_to": apply_to,
        }

        # Assignees can be specified for owner and group and must be specified for custom:
        #
        if assignee:
            permission_post_data["right_id"] = assignee

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/permissions/"
            + assignee_type
        )

        request_header = self.request_form_header()

        logger.info(
            "Assign permissions -> %s to item with ID -> %s; assignee type -> %s; calling -> %s",
            str(permissions),
            str(node_id),
            assignee_type,
            request_url,
        )

        retries = 0
        while True:
            # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
            if assignee_type == "custom":
                # Custom also has a REST POST - we prefer this one as to
                # also allows to add a new assigned permission (user or group):
                response = requests.post(
                    url=request_url,
                    data={"body": json.dumps(permission_post_data)},
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
            else:
                # Owner, Owner Group and Public require REST PUT:
                response = requests.put(
                    url=request_url,
                    data={"body": json.dumps(permission_post_data)},
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign permissions -> %s to item with ID -> %s; status -> %s; error -> %s",
                    str(permissions),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_node_categories(self, node_id: int, metadata: bool = True):
        """Get categories assigned to a node.

        Args:
            node_id (int): ID of the node to get the categories for.
            metadata (bool, optional): expand the attribute definitions of the category. Default is True.
        Returns:
            dict: category response or None if the call to the REST API fails.
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
        if metadata:
            request_url += "?metadata"
        request_header = self.request_form_header()

        logger.info(
            "Get categories of node with ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get categories for node ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_node_category(self, node_id: int, category_id: int, metadata: bool = True):
        """Get a specific category assigned to a node.

        Args:
            node_id (int): ID of the node to get the categories for.
            category_id (int): ID of the category definition ID (in category volume)
            metadata (bool, optional): expand the attribute definitions of the category. Default is True
        Returns:
            dict: category response or None if the call to the REST API fails.
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/categories/"
            + str(category_id)
        )
        if metadata:
            request_url += "?metadata"
        request_header = self.request_form_header()

        logger.info(
            "Get category with ID -> %s on node with ID -> %s; calling -> %s",
            str(category_id),
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get category with ID -> %s for node ID -> %s; status -> %s; error -> %s",
                    str(category_id),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_node_category_ids(self, node_id: int) -> list:
        """Get list of all category definition IDs that are assign to the node.

        Args:
            node_id (int): ID of the node to get the categories for.
        Returns:
            list: list of category IDs (all categories assigned to the node)
        """

        categories = self.get_node_categories(node_id)
        if not categories or not categories["results"]:
            return None

        category_id_list = []

        for category in categories["results"]:
            category_id_list += [
                int(i) for i in category["metadata_order"]["categories"]
            ]

        return category_id_list

    # end method definition

    def get_node_category_definition(
        self, node_id: int, category_name: str
    ) -> tuple[int, dict]:
        """Get category definition (category id and attribute IDs and types)

        Args:
            node_id (int): node to read the category definition from
                           (e.g. a workspace template or a document template or a target folder)
                           This should NOT be the category definition object!
            category_name (str): name of the category
        Returns:
            int: category ID
            dict: keys are the attribute names. values are sub-dictionaries with the id and type of the attribute.

            Example response:
            {
                'Status': {
                    'id': '12532_2',
                    'type': 'String'
                },
                'Legal Approval': {
                    'id': '12532_3',
                    'type': 'user'
                },
                ...
            }
        """

        attribute_definitions = {}
        cat_id = -1

        response = self.get_node_categories(node_id)
        if response and response["results"]:
            for categories in response["results"]:
                keys = categories["metadata"]["categories"].keys()
                cat_id = next((key for key in keys if "_" not in key), -1)
                cat_name = categories["metadata"]["categories"][cat_id]["name"]
                if cat_name != category_name:
                    continue
                for att_id in categories["metadata"]["categories"]:
                    if not "_" in att_id:
                        continue
                    att_name = categories["metadata"]["categories"][att_id]["name"]
                    if categories["metadata"]["categories"][att_id]["persona"]:
                        att_type = categories["metadata"]["categories"][att_id][
                            "persona"
                        ]
                    else:
                        att_type = categories["metadata"]["categories"][att_id][
                            "type_name"
                        ]
                    attribute_definitions[att_name] = {"id": att_id, "type": att_type}
        return cat_id, attribute_definitions

    # end method definition

    def assign_category(
        self,
        node_id: int,
        category_id: list,
        inheritance: bool = False,
        apply_to_sub_items: bool = False,
        apply_action: str = "add_upgrade",
        add_version: bool = False,
        clear_existing_categories: bool = False,
    ) -> bool:
        """Assign a category to a node. Optionally turn on inheritance and apply
           category to sub-items (if node_id is a container / folder / workspace).
           If the category is already assigned to the node this method will
           throw an error.

        Args:
            node_id (int): node ID to apply the category to
            category_id (list): ID of the category definition object
            inheritance (bool): turn on inheritance for the category
                                   (this makes only sense if the node is a container like a folder or workspace)
            apply_to_sub_items (bool, optional): if True the category is applied to
                                                    the item and all its sub-items
                                                    if False the category is only applied
                                                    to the item
            apply_action (str, optional): supported values are "add", "add_upgrade", "upgrade", "replace", "delete", "none", None
            add_version (bool, optional): if a document version should be added for the category change (default = False)
            clear_existing_categories (bool, optional): whether or not existing (other) categories should be removed (default = False)
        Returns:
            bool: True = success, False = error
        """

        request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
        request_header = self.request_form_header()

        #
        # 1. Assign Category to Node if not yet assigned:
        #

        existing_category_ids = self.get_node_category_ids(node_id)
        if not category_id in existing_category_ids:
            logger.info(
                "Category with ID -> %s is not yet assigned to node ID -> %s. Assigning it now...",
                str(category_id),
                str(node_id),
            )
            category_post_data = {
                "category_id": category_id,
            }

            logger.info(
                "Assign category with ID -> %s to item with ID -> %s; calling -> %s",
                str(category_id),
                str(node_id),
                request_url,
            )

            retries = 0
            while True:
                response = requests.post(
                    url=request_url,
                    data=category_post_data,
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
                if response.ok:
                    break
                # Check if Session has expired - then re-authenticate and try once more
                elif response.status_code == 401 and retries == 0:
                    logger.warning("Session has expired - try to re-authenticate...")
                    self.authenticate(revalidate=True)
                    retries += 1
                else:
                    logger.error(
                        "Failed to assign category with ID -> %s to node with ID -> %s; status -> %s; error -> %s",
                        str(category_id),
                        str(node_id),
                        response.status_code,
                        response.text,
                    )
                    return False

        #
        # 2. Set Inheritance
        #

        request_url_inheritance = request_url + "/" + str(category_id) + "/inheritance"

        retries = 0
        while True:
            if inheritance:
                # Enable inheritance
                response = requests.post(
                    url=request_url_inheritance,
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
            else:
                # Disable inheritance
                response = requests.delete(
                    url=request_url_inheritance,
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
            if response.ok:
                break
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to set inheritance for category with ID -> %s on node with ID -> %s; status -> %s; error -> %s",
                    str(category_id),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return False

        #
        # 3. Apply to sub-items
        #

        if apply_to_sub_items:
            request_url_apply_sub_items = request_url + "/apply"

            category_post_data = {
                "categories": [{"id": category_id, "action": apply_action}],
                "add_version": add_version,
                "clear_existing_categories": clear_existing_categories,
            }

            retries = 0
            while True:
                # we need to wrap the body of this POST call into a "body"
                # tag. This is documented worngly on developer.opentext.com
                response = requests.post(
                    url=request_url_apply_sub_items,
                    data={"body": json.dumps(category_post_data)},
                    headers=request_header,
                    cookies=self.cookie(),
                    timeout=None,
                )
                if response.ok:
                    break
                # Check if Session has expired - then re-authenticate and try once more
                elif response.status_code == 401 and retries == 0:
                    logger.warning("Session has expired - try to re-authenticate...")
                    self.authenticate(revalidate=True)
                    retries += 1
                else:
                    logger.error(
                        "Failed to apply category with ID -> %s to sub-items of node with ID -> %s; status -> %s; error -> %s",
                        str(category_id),
                        str(node_id),
                        response.status_code,
                        response.text,
                    )
                    return False
        return True

    # end method definition

    def set_category_value(
        self,
        node_id: int,
        value,
        category_id: int,
        attribute_id: int,
        set_id: int = 0,
        set_row: int = 1,
    ) -> dict | None:
        """Set a value to a specific attribute in a category. Categories and have sets (groupings), multi-line sets (matrix),
           and multi-value attributes (list of values). This method supports all variants.

        Args:
            node_id (int): ID of the node
            value (multi-typed): value to be set - can be string or list of strings (for multi-value attributes)
            category_id (int):ID of the category object
            attribute_id (int): ID of the attribute
            set_id (int, optional): ID of the set. Defaults to 0.
            set_row (int, optional): Row of . Defaults to 1.

        Returns:
            dict: REST API response or None if the call fails
        """

        request_url = (
            self.config()["nodesUrlv2"]
            + "/"
            + str(node_id)
            + "/categories/"
            + str(category_id)
        )
        request_header = self.request_form_header()

        if set_id:
            logger.info(
                "Assign value -> %s to category with ID -> %s, set ID -> %s, row -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
                str(value),
                str(category_id),
                str(set_id),
                str(set_row),
                str(attribute_id),
                str(node_id),
                request_url,
            )
            category_put_data = {
                "category_id": category_id,
                "{}_{}_{}_{}".format(category_id, set_id, set_row, attribute_id): value,
            }
        else:
            logger.info(
                "Assign value -> %s to category ID -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
                str(value),
                str(category_id),
                str(attribute_id),
                str(node_id),
                request_url,
            )
            category_put_data = {
                "category_id": category_id,
                "{}_{}".format(category_id, attribute_id): value,
            }

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                data=category_put_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to set value -> %s for category with ID -> %s, attribute ID -> %s on node ID -> %s; status -> %s; error -> %s",
                    str(value),
                    str(category_id),
                    str(attribute_id),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def assign_classification(
        self, node_id: int, classifications: list, apply_to_sub_items: bool = False
    ) -> dict | None:
        """Assign one or multiple classifications to an Extended ECM item
        Args:
            node_id (int): node ID of the Extended ECM item
            classifications (list): list of classification item IDs
            apply_to_sub_items (bool, optional): if True the classification is applied to
                                                    the item and all its sub-items
                                                    if False the classification is only applied
                                                    to the item
        Returns:
            dict: Response of the request or None if the assignment of the classification has failed.
        """

        # the REST API expects a list of dict elements with "id" and the actual IDs
        classification_list = []
        for classification in classifications:
            classification_list.append({"id": classification})

        classification_post_data = {
            "class_id": classification_list,
            "apply_to_sub_items": apply_to_sub_items,
        }

        request_url = (
            self.config()["nodesUrl"] + "/" + str(node_id) + "/classifications"
        )

        request_header = self.request_form_header()

        logger.info(
            "Assign classifications with IDs -> %s to item with ID -> %s; calling -> %s",
            str(classifications),
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=classification_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign classifications with IDs -> %s to item with ID -> %s; status -> %s; error -> %s",
                    str(classifications),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def assign_rm_classification(
        self, node_id: int, rm_classification: int, apply_to_sub_items: bool = False
    ) -> dict | None:
        """Assign a RM classification to an Extended ECM item
        Args:
            node_id (int): node ID of the Extended ECM item
            rm_classification (int): Records Management classification ID
            apply_to_sub_items (bool, optional): if True the RM classification is applied to
                                                    the item and all its sub-items
                                                    if False the RM classification is only applied
                                                    to the item
        Returns:
            dict: Response of the request or None if the assignment of the RM classification has failed.
        """

        rm_classification_post_data = {
            "class_id": rm_classification,
            "apply_to_sub_items": apply_to_sub_items,
        }

        request_url = (
            self.config()["nodesUrl"] + "/" + str(node_id) + "/rmclassifications"
        )

        request_header = self.request_form_header()

        logger.info(
            "Assign RM classifications with ID -> %s to item with ID -> %s; calling -> %s",
            str(rm_classification),
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=rm_classification_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign RM classifications with ID -> %s to item with ID -> %s; status -> %s; error -> %s",
                    str(rm_classification),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def register_workspace_template(self, node_id: int) -> dict | None:
        """Register a workspace template as project template for Extended ECM for Engineering
        Args:
            node_id (int): node ID of the Extended ECM workspace template
        Returns:
            dict: Response of request or None if the registration of the workspace template has failed.
        """

        registration_post_data = {"ids": "{{ {} }}".format(node_id)}

        request_url = self.config()["xEngProjectTemplateUrl"]

        request_header = self.request_form_header()

        logger.info(
            "Register workspace template with ID -> %s; calling -> %s",
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=registration_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to register Workspace Template with ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_records_management_rsis(self, limit: int = 100) -> list | None:
        """Get all Records management RSIs togther with their RSI Schedules.

        Args:
            limit (int, optional): max elements to return (default = 100)
        Returns:
            list: list of Records Management RSIs or None if the request fails.
            Each RSI list element is a dict with this structure:
            {
                "RSIID": 0,
                "RSI": "string",
                "Title": "string",
                "Subject": "string",
                "Description": "string",
                "CreateDate": "string",
                "RSIStatus": "string",
                "StatusDate": "string",
                "DiscontFlag": 0,
                "DiscontDate": "string",
                "DiscontComment": "string",
                "Active": 0,
                "DispControl": 0,
                "RSIScheduleID": 0,
                "RetStage": "string",
                "RecordType": 0,
                "EventType": 0,
                "RSIRuleCode": "string",
                "DateToUse": "string",
                "YearEndMonth": 0,
                "YearEndDay": 0,
                "RetYears": 0,
                "RetMonths": 0,
                "RetDays": 0,
                "RetIntervals": 0,
                "EventRuleDate": "string",
                "EventRule": "string",
                "EventComment": "string",
                "StageAction": "string",
                "FixedRet": 0,
                "ActionCode": "string",
                "ActionDescription": "string",
                "Disposition": "string",
                "ApprovalFlag": 0,
                "MaximumRet": 0,
                "ObjectType": "LIV"
            }
        """

        request_url = self.config()["rsisUrl"] + "?limit=" + str(limit)
        request_header = self.request_form_header()

        logger.info("Get list of Records Management RSIs; calling -> %s", request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                rsi_dict = self.parse_request_response(response)
                return rsi_dict["results"]["data"]["rsis"]
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get list of Records Management RSIs; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_records_management_codes(self) -> dict | None:
        """Get Records Management Codes. These are the most basic data types of
           the Records Management configuration and required to create RSIs and
           other higher-level Records Management configurations

        Args:
            None
        Returns:
            dict: RM codes or None if the request fails.
        """

        request_url = self.config()["recordsManagementUrlv2"] + "/rmcodes"
        request_header = self.request_form_header()

        logger.info("Get list of Records Management codes; calling -> %s", request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                rm_codes_dict = self.parse_request_response(response)
                return rm_codes_dict["results"]["data"]
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get list of Records Management codes; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    # This is not yet working. REST API endpoint seems not to be in 22.4. Retest with 23.1
    def update_records_management_codes(self, rm_codes: dict) -> dict | None:
        """Update Records Management Codes. These are the most basic data types of
           the Records Management configuration and required to create RSIs and
           other higher-level Records Management configurations
           THIS METHOD IS CURRENTLY NOT WORKING

        Args:
            rm_codes (dict): Codes to be updated
        Returns:
            dict: RSI data or None if the request fails.
        """

        update_rm_codes_post_data = {}

        request_url = self.config()["recordsManagementUrl"] + "/rmcodes"
        request_header = self.request_form_header()

        logger.info(
            "Update Records Management codes -> %s; calling -> %s",
            str(rm_codes),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=update_rm_codes_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                rm_codes_dict = self.parse_request_response(response)
                return rm_codes_dict["results"]["data"]
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to update Records Management codes; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def create_records_management_rsi(
        self,
        name: str,
        status: str,
        status_date: str,
        description: str,
        subject: str,
        title: str,
        dispcontrol: bool,
    ) -> dict | None:
        """Create a new Records Management RSI.

        Args:
            name (str): name of the RSI
            status (str): status of the RSI
            status_date (str): statusDate of the RSI YYYY-MM-DDTHH:mm:ss
            description (str): description of the RSI
            subject (str): status of the RSI
            title (str): status of the RSI
            dispcontrol (bool): status of the RSI
        Returns:
            dict: RSI data or None if the request fails.
        """

        if status_date == "":
            now = datetime.now()
            status_date = now.strftime("%Y-%m-%dT%H:%M:%S")

        create_rsi_post_data = {
            "name": name,
            "status": status,
            "statusDate": status_date,
            "description": description,
            "subject": subject,
            "title": title,
            "dispcontrol": dispcontrol,
        }

        request_url = self.config()["rsiSchedulesUrl"]

        request_header = self.request_form_header()

        logger.info(
            "Create Records Management RSI -> %s; calling -> %s", name, request_url
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=create_rsi_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create Records Management RSI -> %s; status -> %s; error -> %s",
                    name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def create_records_management_rsi_schedule(
        self,
        rsi_id: int,
        stage: str,
        event_type: int = 1,
        object_type: str = "LIV",
        rule_code: str = "",
        rule_comment: str = "",
        date_to_use: int = 91,
        retention_years: int = 0,
        retention_months: int = 0,
        retention_days: int = 0,
        category_id: int = 0,
        attribute_id: int = 0,
        year_end_month: int = 12,
        year_end_day: int = 31,
        retention_intervals: int = 1,
        fixed_retention: bool = True,
        maximum_retention: bool = True,
        fixed_date: str = "",
        event_condition: str = "",
        disposition: str = "",
        action_code: int = 0,
        description: str = "",
        new_status: str = "",
        min_num_versions_to_keep: int = 1,
        purge_superseded: bool = False,
        purge_majors: bool = False,
        mark_official_rendition: bool = False,
    ) -> dict | None:
        """Create a new Records Management RSI Schedule for an existing RSI.

        Args:
            rsi_id (int): ID of an existing RSI the schedule should be created for
            stage (str): retention stage - this is the key parameter to define multiple stages (stages are basically schedules)
            event_type (int): 1 Calculated Date, 2 Calendar Calculation, 3 Event Based, 4 Fixed Date, 5 Permanent
            object_type (str): either "LIV" - Classified Objects (default) or "LRM" - RM Classifications
            rule_code (str, optional): rule code - this value must be defined upfront
            rule_comment (str, optional): comment for the rule
            date_to_use (int, optional): 91 Create Date, 92 Reserved Data, 93 Modification Date, 94 Status Date, 95 Records Date
            retention_years (int, optional): years to wait before disposition
            retention_months (int, optional): month to wait before disposition
            retention_days (int, optional): days to wait before disposition
            category_id (int, optional): ID of the category
            attribute_id (int, optional): ID of the category attribute
            year_end_month (int, optional): month the year ends (default = 12)
            year_end_day (int, optional): day the year ends (default = 31)
            retention_intervals (int, optional): retention intervals
            fixed_retention (bool, optional): fixedRetention
            maximum_retention (bool,optional): maximumRetention
            fixed_date(str, optional): fixed date format : YYYY-MM-DDTHH:mm:ss
            event_condition (str, optional): eventCondition
            disposition (str, optional): disposition
            action_code (int, optional): 0 None, 1 Change Status, 7 Close, 8 Finalize Record, 9 Mark Official, 10 Export, 11 Update Storage Provider, 12 Delete Electronic Format, 15 Purge Versions, 16 Make Rendition, 32 Destroy
            description (str, optional): description
            new_status (str, optional): new status
            min_num_versions_to_keep (int, optional): minimum document versions to keep, . Default is 1.
            purge_superseded (bool, optional): purge superseded. Default is False.
            purge_majors (bool, optional): purge majors. Default is False.
            mark_official_rendition (bool, optional): mark official rendition. Default is False.
        Returns:
            dict: RSI Schedule data or None if the request fails.
        """

        if fixedDate == "":
            now = datetime.now()
            fixedDate = now.strftime("%Y-%m-%dT%H:%M:%S")

        create_rsi_schedule_post_data = {
            "objectType": object_type,
            "stage": stage,
            "eventType": event_type,
            "ruleCode": rule_code,
            "ruleComment": rule_comment,
            "dateToUse": date_to_use,
            "retentionYears": retention_years,
            "retentionMonths": retention_months,
            "retentionDays": retention_days,
            "categoryId": category_id,
            "attributeId": attribute_id,
            "yearEndMonth": year_end_month,
            "yearEndDay": year_end_day,
            "retentionIntervals": retention_intervals,
            "fixedRetention": fixed_retention,
            "maximumRetention": maximum_retention,
            "fixedDate": fixed_date,
            "eventCondition": event_condition,
            "disposition": disposition,
            "actionCode": action_code,
            "description": description,
            "newStatus": new_status,
            "minNumVersionsToKeep": min_num_versions_to_keep,
            "purgeSuperseded": purge_superseded,
            "purgeMajors": purge_majors,
            "markOfficialRendition": mark_official_rendition,
        }

        request_url = self.config()["rsiSchedulesUrl"] + "/" + str(rsi_id) + "/stages"

        request_header = self.request_form_header()

        logger.info(
            "Create Records Management RSI Schedule -> %s for RSI -> %s; calling -> %s",
            stage,
            str(rsi_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=create_rsi_schedule_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create Records Management RSI Schedule -> %s; status -> %s; error -> %s",
                    stage,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def create_records_management_hold(
        self,
        hold_type: str,
        name: str,
        comment: str,
        alternate_id: str = "",
        parent_id: int = 0,
        date_applied: str = "",
        date_to_remove: str = "",
    ) -> dict | None:
        """Create a new Records Management Hold.

        Args:
            hold_type (str): type of the Hold
            name (str): name of the RSI
            comment (str): comment
            alternate_id (str, optional): alternate hold ID
            parent_id (int, optional): ID of the parent node. If parent_id is 0 the item will be created right under "Hold Management" (top level item)
            date_applied (str, optional): create date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
            date_to_remove (str, optional): suspend date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
        Returns:
            dict: Hold data or None if the request fails. The dict structure is this: {'holdID': <ID>}
        """

        if date_applied == "":
            now = datetime.now()
            date_applied = now.strftime("%Y-%m-%dT%H:%M:%S")

        create_hold_post_data = {
            "type": hold_type,
            "name": name,
            "comment": comment,
            "date_applied": date_applied,
            "date_to_remove": date_to_remove,
            "alternate_id": alternate_id,
        }

        if parent_id > 0:
            create_hold_post_data["parent_id"] = parent_id

        request_url = self.config()["holdsUrl"]

        request_header = self.request_form_header()

        logger.info(
            "Create Records Management Hold -> %s; calling -> %s", name, request_url
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=create_hold_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to create Records Management Hold -> %s; status -> %s; error -> %s",
                    name,
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def get_records_management_holds(self) -> dict | None:
        """Get a list of all Records Management Holds in the system. Even though there are folders
        in the holds management area in RM these are not real folders - they cannot be retrieved
        with get_node_by_parent_and_name() thus we need this method to get them all.

        Args:
            None
        Returns:
            dict: Response with list of holds:
            "results": {
                "data": {
                    "holds": [
                        {
                            "HoldID": 0,
                            "HoldName": "string",
                            "ActiveHold": 0,
                            "OBJECT": 0,
                            "ApplyPatron": "string",
                            "DateApplied": "string",
                            "HoldComment": "string",
                            "HoldType": "string",
                            "DateToRemove": "string",
                            "DateRemoved": "string",
                            "RemovalPatron": "string",
                            "RemovalComment": "string",
                            "EditDate": "string",
                            "EditPatron": "string",
                            "AlternateHoldID": 0,
                            "ParentID": 0
                        }
                    ]
                }
            }
        """

        request_url = self.config()["holdsUrlv2"]

        request_header = self.request_form_header()

        logger.info("Get list of Records Management Holds; calling -> %s", request_url)

        retries = 0
        while True:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get list of Records Management Holds; status -> %s; error -> %s",
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def import_records_management_settings(self, file_path: str) -> bool:
        """Import Records Management settings from a file that is uploaded from the python pod

        Args:
            file_path (str): path + filename of config file in Python container filesystem
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["recordsManagementUrl"] + "/importSettings"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Records Management Settings from file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Records Management Settings from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def import_records_management_codes(
        self, file_path: str, update_existing_codes: bool = True
    ) -> bool:
        """Import RM Codes from a file that is uploaded from the python pod
        Args:
            file_path (str): path + filename of settings file in Python container filesystem
            update_existing_codes (bool): Flag that controls whether existing table maintenance codes
                                          should be updated.
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["recordsManagementUrl"] + "/importCodes"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Records Management Codes from file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {"updateExistingCodes": update_existing_codes}

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=settings_post_data,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Records Management Codes from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def import_records_management_rsis(
        self,
        file_path: str,
        update_existing_rsis: bool = True,
        delete_schedules: bool = False,
    ) -> bool:
        """Import RM RSIs from a config file that is uploaded from the Python pod
        Args:
            file_path (str): path + filename of config file in Python container filesystem
            update_existing_rsis (bool, optional): whether or not existing RSIs should be updated (or ignored)
            delete_schedules (bool, optional): whether RSI Schedules should be deleted
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["recordsManagementUrl"] + "/importRSIs"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Records Management RSIs from file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {
            "updateExistingRSIs": update_existing_rsis,
            "deleteSchedules": delete_schedules,
        }

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=settings_post_data,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Records Management RSIs from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def import_physical_objects_settings(self, file_path: str) -> bool:
        """Import Physical Objects settings from a config file that is uploaded from the python pod
        Args:
            file_path (str): path + filename of config file in Python container filesystem
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["physicalObjectsUrl"] + "/importSettings"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Physical Objects Settings from server file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Physical Objects settings from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def import_physical_objects_codes(
        self, file_path: str, update_existing_codes: bool = True
    ) -> bool:
        """Import Physical Objects codes from a config file that is uploaded from the Python pod
        Args:
            file_path (str): path + filename of config file in Python container filesystem
            update_existing_codes (bool): whether or not existing codes should be updated (default = True)
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["physicalObjectsUrl"] + "/importCodes"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Physical Objects Codes from file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {"updateExistingCodes": update_existing_codes}

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=settings_post_data,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Physical Objects Codes from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def import_physical_objects_locators(self, file_path: str) -> bool:
        """Import Physical Objects locators from a config file that is uploaded from the python pod
        Args:
            file_path (str): path + filename of config file in Python container filesystem
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["physicalObjectsUrl"] + "/importLocators"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Physical Objects Locators from file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Physical Objects Locators from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def import_security_clearance_codes(
        self, file_path: str, include_users: bool = False
    ) -> bool:
        """Import Security Clearance codes from a config file that is uploaded from the python pod
        Args:
            file_path (str): path + filename of config file in Python container filesystem
            include_users (bool): defines if users should be included or not
        Returns:
            bool: True if if the REST call succeeds or False otherwise.
        """

        request_url = self.config()["securityClearancesUrl"] + "/importCodes"

        request_header = (
            self.cookie()
        )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

        logger.info(
            "Importing Security Clearance Codes from file -> %s; calling -> %s",
            file_path,
            request_url,
        )

        settings_post_data = {"includeusers": include_users}

        filename = os.path.basename(file_path)
        if not os.path.exists(file_path):
            logger.error(
                "The file -> %s does not exist in path -> %s!",
                filename,
                os.path.dirname(file_path),
            )
            return False
        settings_post_file = {
            "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
        }

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=settings_post_data,
                files=settings_post_file,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return True
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to import Security Clearance Codes from file -> %s; status -> %s; error -> %s",
                    file_path,
                    response.status_code,
                    response.text,
                )
                return False

    # end method definition

    def assign_user_security_clearance(
        self, user_id: int, security_clearance: int
    ) -> dict | None:
        """Assign a Security Clearance level to an Extended ECM user

        Args:
            user_id (int): ID of the user
            security_clearance (int): security clearance level to be set
        Returns:
            dict: REST response or None if the REST call fails.
        """

        assign_user_security_clearance_post_data = {
            "securityLevel": security_clearance,
        }

        request_url = self.config()[
            "userSecurityUrl"
        ] + "/{}/securityclearancelevel".format(user_id)
        request_header = self.request_form_header()

        logger.info(
            "Assign security clearance -> %s to user with ID -> %s; calling -> %s",
            str(security_clearance),
            str(user_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=assign_user_security_clearance_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign security clearance -> %s to user with ID -> %s; status -> %s; error -> %s",
                    str(security_clearance),
                    str(user_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def assign_user_supplemental_markings(
        self, user_id: int, supplemental_markings: list
    ) -> dict | None:
        """Assign a list of Supplemental Markings to a user

        Args:
            user_id (int): ID of the user
            supplemental_markings (list of strings): list of Supplemental Markings to be set
        Returns:
            dict: REST response or None if the REST call fails.
        """

        assign_user_supplemental_markings_post_data = {
            "suppMarks": supplemental_markings,
        }

        request_url = self.config()[
            "userSecurityUrl"
        ] + "/{}/supplementalmarkings".format(user_id)
        request_header = self.request_form_header()

        logger.info(
            "Assign supplemental markings -> %s to user with ID -> %s; calling -> %s",
            str(supplemental_markings),
            str(user_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                headers=request_header,
                data=assign_user_supplemental_markings_post_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign supplemental markings -> %s to user with ID -> %s; status -> %s; error -> %s",
                    str(supplemental_markings),
                    str(user_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def check_workspace_aviator(
        self,
        workspace_id: int,
    ) -> bool:
        """Check if Content Aviator is enabled for a workspace

        Args:
            workspace_id (int): node ID of the workspace
        Returns:
            bool: True if aviator is enabled, False otherwise
        """

        response = self.get_node_actions(
            node_id=workspace_id, filter_actions=["disableai", "enableai"]
        )
        result_data = self.get_result_value(
            response=response,
            key=str(workspace_id),
        )
        if result_data and "data" in result_data:
            data = result_data["data"]
            if "disableai" in data:
                logger.info(
                    "Aviator is enabled for workspace with ID -> %s", str(workspace_id)
                )
                return True
            elif "enableai" in data:
                logger.info(
                    "Aviator is disabled for workspace with ID -> %s", str(workspace_id)
                )

        return False

    # end method definition

    def update_workspace_aviator(
        self,
        workspace_id: int,
        status: bool,
    ) -> dict | None:
        """Enable or disable the Content Aviator for a workspace

        Args:
            workspace_id (int): node ID of the workspace
            status (bool): True = enable, False = disable Content Aviator for this workspace
        Returns:
            dict: REST response or None if the REST call fails.
        """

        aviator_status_put_data = {
            "enabled": status,
        }

        request_url = self.config()["aiUrl"] + "/{}".format(workspace_id)
        request_header = self.request_form_header()

        if status is True:
            logger.info(
                "Enable Content Aviator for workspace with ID -> %s; calling -> %s",
                str(workspace_id),
                request_url,
            )
        else:
            logger.info(
                "Disable Content Aviator for workspace with ID -> %s; calling -> %s",
                str(workspace_id),
                request_url,
            )

        retries = 0
        while True:
            response = requests.put(
                url=request_url,
                headers=request_header,
                data=aviator_status_put_data,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to change status for Content Aviator on workspace with ID -> %s; status -> %s; error -> %s",
                    str(workspace_id),
                    response.status_code,
                    response.text,
                )
                return None

    # end method definition

    def volume_translator(
        self,
        current_node_id: int,
        translator: object,
        languages: list,
        simulate: bool = False,
    ):
        """Experimental code to translate the item names and item descriptions in a given hierarchy.
           The actual translation is done by a tranlator object. This recursive method just
           traverses the hierarchy and calls the translate() method of the translator object.

        Args:
            current_node_id (int): current node ID to translate
            translator (object): this object needs to be created based on the "Translator" class
                                 and passed to this method
            languages (list): list of target languages
            simulate (bool, optional): if True, do not really rename but just traverse and log info.
                                       the default is False
        """
        # Get current node based on the ID:
        current_node = self.get_node(current_node_id)
        current_node_id = self.get_result_value(current_node, "id")

        name = self.get_result_value(current_node, "name")
        description = self.get_result_value(current_node, "description")
        names_multilingual = self.get_result_value(current_node, "name_multilingual")
        descriptions_multilingual = self.get_result_value(
            current_node, "description_multilingual"
        )

        for language in languages:
            if language == "en":
                continue
            # Does the language not exist as metadata language or is it already translated?
            # Then we skip this language:
            if (
                language in names_multilingual
                and names_multilingual["en"]
                and not names_multilingual[language]
            ):
                names_multilingual[language] = translator.translate(
                    "en", language, names_multilingual["en"]
                )
                logger.info(
                    "Translate name of node -> %s from -> %s (%s) to -> %s (%s)",
                    current_node_id,
                    name,
                    "en",
                    names_multilingual[language],
                    language,
                )
            if (
                language in descriptions_multilingual
                and descriptions_multilingual["en"]
                and not descriptions_multilingual[language]
            ):
                descriptions_multilingual[language] = translator.translate(
                    "en", language, descriptions_multilingual["en"]
                )
                logger.info(
                    "Translate description of node -> %s from -> %s (%s) to -> %s (%s)",
                    current_node_id,
                    name,
                    "en",
                    names_multilingual[language],
                    language,
                )

        # Rename node multi-lingual:
        if not simulate:
            self.rename_node(
                current_node_id,
                name,
                description,
                names_multilingual,
                descriptions_multilingual,
            )

        # Get children nodes of the current node:
        results = self.get_subnodes(current_node_id, limit=200)["results"]

        # Recursive call of all subnodes:
        for result in results:
            self.volume_translator(
                result["data"]["properties"]["id"], translator, languages
            )

__init__(protocol, hostname, port, public_url, username=None, password=None, user_partition='Content Server Members', resource_name='cs', default_license='X3', otds_ticket=None, base_path='/cs/cs')

Initialize the OTCS object

Parameters:

Name Type Description Default
protocol str

Either http or https.

required
hostname str

The hostname of Extended ECM server to communicate with.

required
port int

The port number used to talk to the Extended ECM server.

required
public_url str

public (external) URL

required
username str

The admin user name of Extended ECM. Optional if otds_ticket is provided.

None
password str

The admin password of Extended ECM. Optional if otds_ticket is provided.

None
user_partition str

Name of the OTDS partition for OTCS users. Default is "Content Server Members".

'Content Server Members'
resource_name str

Name of the OTDS resource for OTCS. Dault is "cs".

'cs'
default_license str

name of the default user license. Default is "X3".

'X3'
otds_ticket str

Authentication ticket of OTDS

None
Source code in pyxecm/otcs.py
def __init__(
    self,
    protocol: str,
    hostname: str,
    port: int,
    public_url: str,
    username: str | None = None,
    password: str | None = None,
    user_partition: str = "Content Server Members",
    resource_name: str = "cs",
    default_license: str = "X3",
    otds_ticket: str | None = None,
    base_path: str = "/cs/cs",
):
    """Initialize the OTCS object

    Args:
        protocol (str): Either http or https.
        hostname (str): The hostname of Extended ECM server to communicate with.
        port (int): The port number used to talk to the Extended ECM server.
        public_url (str): public (external) URL
        username (str, optional): The admin user name of Extended ECM. Optional if otds_ticket is provided.
        password (str, optional): The admin password of Extended ECM. Optional if otds_ticket is provided.
        user_partition (str): Name of the OTDS partition for OTCS users. Default is "Content Server Members".
        resource_name (str, optional): Name of the OTDS resource for OTCS. Dault is "cs".
        default_license (str, optional): name of the default user license. Default is "X3".
        otds_ticket (str, optional): Authentication ticket of OTDS
    """

    # Initialize otcs_config as an empty dictionary
    otcs_config = {}

    if hostname:
        otcs_config["hostname"] = hostname
    else:
        otcs_config["hostname"] = "otcs-admin-0"

    if protocol:
        otcs_config["protocol"] = protocol
    else:
        otcs_config["protocol"] = "http"

    if port:
        otcs_config["port"] = port
    else:
        otcs_config["port"] = 8080

    otcs_config["publicUrl"] = public_url

    if username:
        otcs_config["username"] = username
    else:
        otcs_config["username"] = "admin"

    if password:
        otcs_config["password"] = password
    else:
        otcs_config["password"] = ""

    if user_partition:
        otcs_config["partition"] = user_partition
    else:
        otcs_config["partition"] = ""

    if resource_name:
        otcs_config["resource"] = resource_name
    else:
        otcs_config["resource"] = ""

    if default_license:
        otcs_config["license"] = default_license
    else:
        otcs_config["license"] = ""

    otcs_base_url = protocol + "://" + otcs_config["hostname"]
    if str(port) not in ["80", "443"]:
        otcs_base_url += ":{}".format(port)
    otcs_config["baseUrl"] = otcs_base_url
    otcs_support_url = otcs_base_url + "/cssupport"
    otcs_config["supportUrl"] = otcs_support_url
    otcs_public_support_url = public_url + "/cssupport"
    otcs_config["supportPublicUrl"] = otcs_public_support_url

    otcs_config["configuredUrl"] = otcs_support_url + "/csconfigured"

    otcs_url = otcs_base_url + base_path
    otcs_config["csUrl"] = otcs_url
    otcs_public_url = public_url + base_path
    otcs_config["csPublicUrl"] = otcs_public_url

    otcs_rest_url = otcs_url + "/api"
    otcs_config["restUrl"] = otcs_rest_url

    otcs_config["isReady"] = otcs_rest_url + "/v1/ping"
    otcs_config["authenticationUrl"] = otcs_rest_url + "/v1/auth"
    otcs_config["serverInfoUrl"] = otcs_rest_url + "/v1/serverinfo"
    otcs_config["membersUrl"] = otcs_rest_url + "/v1/members"
    otcs_config["membersUrlv2"] = otcs_rest_url + "/v2/members"
    otcs_config["nodesUrl"] = otcs_rest_url + "/v1/nodes"
    otcs_config["nodesUrlv2"] = otcs_rest_url + "/v2/nodes"
    otcs_config["doctemplatesUrl"] = otcs_rest_url + "/v2/doctemplates"
    otcs_config["nicknameUrl"] = otcs_rest_url + "/v2/nicknames"
    otcs_config["importSettingsUrl"] = otcs_rest_url + "/v2/import/settings/admin"
    otcs_config["searchUrl"] = otcs_rest_url + "/v2/search"
    otcs_config["volumeUrl"] = otcs_rest_url + "/v2/volumes"
    otcs_config["externalSystemUrl"] = otcs_rest_url + "/v2/externalsystems"
    otcs_config["businessObjectsUrl"] = otcs_rest_url + "/v2/businessobjects"
    otcs_config["businessObjectTypesUrl"] = (
        otcs_rest_url + "/v2/businessobjecttypes"
    )
    otcs_config["businessObjectsSearchUrl"] = (
        otcs_rest_url + "/v2/forms/businessobjects/search"
    )
    otcs_config["businessWorkspaceTypesUrl"] = (
        otcs_rest_url + "/v2/businessworkspacetypes"
    )
    otcs_config["businessworkspacecreateform"] = (
        otcs_rest_url + "/v2/forms/businessworkspaces/create"
    )
    otcs_config["businessWorkspacesUrl"] = otcs_rest_url + "/v2/businessworkspaces"
    otcs_config["uniqueNamesUrl"] = otcs_rest_url + "/v2/uniquenames"
    otcs_config["favoritesUrl"] = otcs_rest_url + "/v2/members/favorites"
    otcs_config["webReportsUrl"] = otcs_rest_url + "/v1/webreports"
    otcs_config["csApplicationsUrl"] = otcs_rest_url + "/v2/csapplications"
    otcs_config["xEngProjectTemplateUrl"] = (
        otcs_rest_url + "/v2/xengcrt/projecttemplate"
    )
    otcs_config["rsisUrl"] = otcs_rest_url + "/v2/rsis"
    otcs_config["rsiSchedulesUrl"] = otcs_rest_url + "/v2/rsischedules"
    otcs_config["recordsManagementUrl"] = otcs_rest_url + "/v1/recordsmanagement"
    otcs_config["recordsManagementUrlv2"] = otcs_rest_url + "/v2/recordsmanagement"
    otcs_config["userSecurityUrl"] = otcs_rest_url + "/v2/members/usersecurity"
    otcs_config["physicalObjectsUrl"] = otcs_rest_url + "/v1/physicalobjects"
    otcs_config["securityClearancesUrl"] = otcs_rest_url + "/v1/securityclearances"
    otcs_config["holdsUrl"] = otcs_rest_url + "/v1/holds"
    otcs_config["holdsUrlv2"] = otcs_rest_url + "/v2/holds"
    otcs_config["validationUrl"] = otcs_rest_url + "/v1/validation/nodes/names"
    otcs_config["aiUrl"] = otcs_rest_url + "/v2/ai/nodes"

    self._config = otcs_config
    self._otds_ticket = otds_ticket

add_document_version(node_id, file_url, file_name, mime_type='text/plain', description='')

Fetch a file from a URL or local filesystem and upload it as a new document version.

Parameters:

Name Type Description Default
node_id int

ID of the document to add add version to

required
file_url str

URL to download file or local file

required
file_name str

name of the file

required
mime_type str

mimeType of the file (default = text/plain)

'text/plain'
description str

description of the version (default = no description)

''

Returns: dict: Add version response or None if the upload fails.

Source code in pyxecm/otcs.py
def add_document_version(
    self,
    node_id: int,
    file_url: str,
    file_name: str,
    mime_type: str = "text/plain",
    description: str = "",
) -> dict | None:
    """Fetch a file from a URL or local filesystem and upload it as a new document version.

    Args:
        node_id (int): ID of the document to add add version to
        file_url (str): URL to download file or local file
        file_name (str): name of the file
        mime_type (str, optional): mimeType of the file (default = text/plain)
        description (str, optional): description of the version (default = no description)
    Returns:
        dict: Add version response or None if the upload fails.
    """

    if file_url.startswith("http"):
        # Download file from remote location specified by the file_url parameter
        # this must be a public place without authentication:
        logger.info("Download file from URL -> %s", file_url)

        try:
            response = requests.get(
                url=file_url,
                timeout=None,
            )
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return None
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return None
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return None
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return None

        logger.info(
            "Successfully downloaded file -> %s; status code -> %s",
            file_url,
            response.status_code,
        )
        file_content = response.content

    elif os.path.exists(file_url):
        logger.info("Uploading local file -> %s", file_url)
        file_content = open(file=file_url, mode="rb")

    else:
        logger.warning("Cannot access -> %s", file_url)
        return None

    upload_post_data = {"description": description}
    upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/versions"
    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 500 response

    logger.info(
        "Uploading file -> %s with mime type -> %s as new version to document node with ID -> %s; calling -> %s",
        file_name,
        mime_type,
        node_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=upload_post_data,
            files=upload_post_files,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to add file -> %s as new version to document with ID -> %s; status -> %s; error -> %s",
                file_url,
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

add_external_system_connection(connection_name, connection_type, as_url, base_url, username, password, authentication_method='BASIC', client_id=None, client_secret=None)

Add Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

Parameters:

Name Type Description Default
connection_name str

Name of the connection

required
connection_type str

Type of the connection (HTTP, SF, SFInstance)

required
as_url str

Application URL of the external system

required
base_url str

Base URL of the external system

required
username str

username (used for BASIC authentication)

required
password str

password (used for BASIC authentication)

required
authentication_method str

either BASIC (using username and password) or OAUTH

'BASIC'
client_id str

OAUTH Client ID (only required if authenticationMethod = OAUTH)

None
client_secret str

OAUTH Client Secret (only required if authenticationMethod = OAUTH)

None

Returns: dict: External system Details or None if the REST call fails.

Source code in pyxecm/otcs.py
def add_external_system_connection(
    self,
    connection_name: str,
    connection_type: str,
    as_url: str,
    base_url: str,
    username: str,
    password: str,
    authentication_method: str = "BASIC",  # either BASIC or OAUTH
    client_id: str = None,
    client_secret: str = None,
) -> dict | None:
    """Add Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

    Args:
        connection_name (str): Name of the connection
        connection_type (str): Type of the connection (HTTP, SF, SFInstance)
        as_url (str): Application URL of the external system
        base_url (str): Base URL of the external system
        username (str): username (used for BASIC authentication)
        password (str): password (used for BASIC authentication)
        authentication_method (str, optional): either BASIC (using username and password) or OAUTH
        client_id (str, optional): OAUTH Client ID (only required if authenticationMethod = OAUTH)
        client_secret (str, optional): OAUTH Client Secret (only required if authenticationMethod = OAUTH)
    Returns:
        dict: External system Details or None if the REST call fails.
    """

    external_system_post_body = {
        "external_system_name": connection_name,
        "conn_type": connection_type,
        "asurl": as_url,
        "baseurl": base_url,
        "username": username,
        "password": password,
    }

    if authentication_method == "OAUTH" and client_id and client_secret:
        external_system_post_body["authentication_method"] = str(
            authentication_method
        )
        external_system_post_body["client_id"] = str(client_id)
        external_system_post_body["client_secret"] = str(client_secret)

    request_url = self.config()["externalSystemUrl"]
    request_header = self.cookie()

    logger.info(
        "Creating external system connection -> %s of type -> %s with URL -> %s; calling -> %s",
        connection_name,
        connection_type,
        as_url,
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=external_system_post_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create external system connection -> %s; status -> %s; error -> %s",
                connection_name,
                response.status_code,
                response.text,
            )
            return None

add_favorite(node_id)

Add a favorite for the current (authenticated) user.

Parameters:

Name Type Description Default
node_id int

ID of the node.

required

Returns: dict: Request response or None if the favorite creation has failed.

Source code in pyxecm/otcs.py
def add_favorite(self, node_id: int) -> dict | None:
    """Add a favorite for the current (authenticated) user.

    Args:
        node_id (int): ID of the node.
    Returns:
        dict: Request response or None if the favorite creation has failed.
    """

    request_url = self.config()["favoritesUrl"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.info(
        "Adding favorite for node ID -> %s; calling -> %s", node_id, request_url
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to add favorite for node ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

add_favorite_tab(tab_name, order)

Add a favorite tab for the current (authenticated) user.

Parameters:

Name Type Description Default
tab_name str

Name of the new tab.

required
order int

The order of the tab.

required

Returns: dict: Request response or None if the favorite tab creation has failed.

Source code in pyxecm/otcs.py
def add_favorite_tab(self, tab_name: str, order: int) -> dict | None:
    """Add a favorite tab for the current (authenticated) user.

    Args:
        tab_name (str): Name of the new tab.
        order (int): The order of the tab.
    Returns:
        dict: Request response or None if the favorite tab creation has failed.
    """

    favorite_tab_post_body = {"name": tab_name, "order": str(order)}

    request_url = self.config()["favoritesUrl"] + "/tabs"
    request_header = self.request_form_header()

    logger.info("Adding favorite tab -> %s; calling -> %s", tab_name, request_url)

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=favorite_tab_post_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to add favorite tab -> %s; status -> %s; error -> %s",
                tab_name,
                response.status_code,
                response.text,
            )
            return None

add_group(name)

Add Content Server group.

Parameters:

Name Type Description Default
name str

name of the group

required

Returns: dict: Group information or None if the group couldn't be created (e.g. because it exisits already).

Source code in pyxecm/otcs.py
def add_group(self, name: str) -> dict | None:
    """Add Content Server group.

    Args:
        name (str): name of the group
    Returns:
        dict: Group information or None if the group couldn't be created (e.g. because it exisits already).
    """

    group_post_body = {"type": 1, "name": name}

    request_url = self.config()["membersUrlv2"]
    request_header = self.request_form_header()

    logger.info("Adding group -> %s; calling -> %s", name, request_url)
    logger.debug("Group Attributes -> %s", str(group_post_body))

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=group_post_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to add group -> %s; status -> %s; error -> %s",
                name,
                response.status_code,
                response.text,
            )
            return None

add_group_member(member_id, group_id)

Add a user or group to a target group.

Parameters:

Name Type Description Default
member_id int

ID of the user or group to add.

required
group_id int

ID of the target group.

required

Returns: dict: Response or None if adding a the member fails.

Source code in pyxecm/otcs.py
def add_group_member(self, member_id: int, group_id: int) -> dict | None:
    """Add a user or group to a target group.

    Args:
        member_id (int): ID of the user or group to add.
        group_id (int): ID of the target group.
    Returns:
        dict: Response or None if adding a the member fails.
    """

    group_member_post_body = {"member_id": member_id}

    request_url = self.config()["membersUrlv2"] + "/" + str(group_id) + "/members"
    request_header = self.request_form_header()

    logger.info(
        "Adding member with ID -> %s to group with ID -> %s; calling -> %s",
        str(member_id),
        str(group_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=group_member_post_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to add member with ID -> %s to group with ID -> %s; status -> %s; error -> %s",
                str(member_id),
                str(group_id),
                response.status_code,
                response.text,
            )
            return None

add_member_to_workspace(workspace_id, role_id, member_id, show_warning=True)

Add member to a workspace role. Check that the user/group is not yet a member.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
role_id int

ID of the role

required
member_id int

User ID or Group ID

required
show_warning bool

If True logs a warning if member is already in role

True

Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def add_member_to_workspace(
    self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
) -> dict | None:
    """Add member to a workspace role. Check that the user/group is not yet a member.

    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        member_id (int): User ID or Group ID
        show_warning (bool, optional): If True logs a warning if member is already in role
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    add_member_to_workspace_post_data = {"id": str(member_id)}

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/roles/{}/members".format(workspace_id, role_id)
    request_header = self.request_form_header()

    logger.info(
        "Check if user/group with ID -> %s is already in role with ID -> %s of workspace with ID -> %s; calling -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
        request_url,
    )

    response = requests.get(
        url=request_url,
        headers=request_header,
        cookies=self.cookie(),
        timeout=None,
    )
    if not response.ok:
        logger.error(
            "Failed to get workspace members; status -> %s; error -> %s",
            response.status_code,
            response.text,
        )
        return None

    workspace_members = self.parse_request_response(response)

    if self.exist_result_item(workspace_members, "id", member_id):
        if show_warning:
            logger.warning(
                "User/group with ID -> %s is already a member of role with ID -> %s of workspace with ID -> %s",
                str(member_id),
                str(role_id),
                str(workspace_id),
            )
        return workspace_members

    logger.info(
        "Add user/group with ID -> %s to role with ID -> %s of workspace with ID -> %s; calling -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
        request_url,
    )

    response = requests.post(
        url=request_url,
        headers=request_header,
        data=add_member_to_workspace_post_data,
        cookies=self.cookie(),
        timeout=None,
    )

    if response.ok:
        return self.parse_request_response(response)
    else:
        logger.error(
            "Failed to add user/group with ID -> %s to role with ID -> %s of workspace with ID -> %s; status -> %s; error -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            response.status_code,
            response.text,
        )
        return None

add_user(name, password, first_name, last_name, email, title, base_group, privileges=None)

Add Content Server user.

Parameters:

Name Type Description Default
name str

login name of the user

required
password str

password of the user

required
first_name str

first name of the user

required
last_name str

last name of the user

required
email str

email address of the user

required
title str

title of the user

required
base_group int

base group id of the user (e.g. department)

required
privileges list

values are Login, Public Access, Content Manager, Modify Users, Modify Groups, User Admin Rights, Grant Discovery, System Admin Rights

None

Returns: dict: User information or None if the user couldn't be created (e.g. because it exisits already).

Source code in pyxecm/otcs.py
def add_user(
    self,
    name: str,
    password: str,
    first_name: str,
    last_name: str,
    email: str,
    title: str,
    base_group: int,
    privileges: list | None = None,
) -> dict | None:
    """Add Content Server user.

    Args:
        name (str): login name of the user
        password (str): password of the user
        first_name (str): first name of the user
        last_name (str): last name of the user
        email (str): email address of the user
        title (str): title of the user
        base_group (int): base group id of the user (e.g. department)
        privileges (list, optional): values are Login, Public Access, Content Manager,
                                     Modify Users, Modify Groups, User Admin Rights,
                                     Grant Discovery, System Admin Rights
    Returns:
        dict: User information or None if the user couldn't be created (e.g. because it exisits already).
    """

    if privileges is None:
        privileges = ["Login", "Public Access"]

    user_post_body = {
        "type": 0,
        "name": name,
        "password": password,
        "first_name": first_name,
        "last_name": last_name,
        "business_email": email,
        "title": title,
        "group_id": base_group,
        "privilege_login": ("Login" in privileges),
        "privilege_public_access": ("Public Access" in privileges),
        "privilege_content_manager": ("Content Manager" in privileges),
        "privilege_modify_users": ("Modify Users" in privileges),
        "privilege_modify_groups": ("Modify Groups" in privileges),
        "privilege_user_admin_rights": ("User Admin Rights" in privileges),
        "privilege_grant_discovery": ("Grant Discovery" in privileges),
        "privilege_system_admin_rights": ("System Admin Rights" in privileges),
    }

    request_url = self.config()["membersUrlv2"]
    request_header = self.request_form_header()

    logger.info("Adding user -> %s; calling -> %s", name, request_url)

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=user_post_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to add user -> %s; status -> %s; error -> %s",
                name,
                response.status_code,
                response.text,
            )
            return None

add_user_proxy(proxy_user_id, from_date=None, to_date=None)

Add a user as a proxy user to the current user. IMPORTANT: This method needs to be called as the user the proxy is acting for. Optional this method can be provided with a time span the proxy should be active. This method differentiates between the old (xGov) based implementation and the new Extended ECM platform one that was introduced with version 23.4.

Example payload for proxy user 19340 without time span: {"id":2545, "from_date": None, "to_date": None}

Example payload for proxy user 19340 with time span: {"id":2545, "from_date":"2023-03-15", "to_date":"2023-03-31"}

Parameters:

Name Type Description Default
user_id int

ID of the user

required
from_date str

start date for proxy (format YYYY-MM-DD)

None
to_date str

end date for proxy (format YYYY-MM-DD)

None

Returns: dict: Request response or None if call fails.

Source code in pyxecm/otcs.py
def add_user_proxy(
    self,
    proxy_user_id: int,
    from_date: str = None,
    to_date: str = None,
) -> dict | None:
    """Add a user as a proxy user to the current user.
       IMPORTANT: This method needs to be called as the user the proxy is acting for.
       Optional this method can be provided with a time span the proxy should be active.
       This method differentiates between the old (xGov) based
       implementation and the new Extended ECM platform one
       that was introduced with version 23.4.

       Example payload for proxy user 19340 without time span:
       {"id":2545, "from_date": None, "to_date": None}

       Example payload for proxy user 19340 with time span:
       {"id":2545, "from_date":"2023-03-15", "to_date":"2023-03-31"}

    Args:
        user_id (int): ID of the user
        from_date (str, optional): start date for proxy (format YYYY-MM-DD)
        to_date (str, optional): end date for proxy (format YYYY-MM-DD)
    Returns:
        dict: Request response or None if call fails.
    """

    version_number = self.get_server_version()
    # Split the version number by dot
    parts = version_number.split(".")
    # Take the first two parts and join them back with a dot
    stripped_version = ".".join(parts[:2])
    version_number = float(stripped_version)

    # for versions older than 23.4 we need to use
    # the egacy Extended ECM for Government Proxy
    # implementation:
    if version_number >= 23.4:
        post_dict = {}
        post_dict["id"] = proxy_user_id
        post_dict["from_date"] = from_date
        post_dict["to_date"] = to_date
        post_data = {"body": json.dumps(post_dict)}
        request_url = self.config()["membersUrlv2"] + "/proxies"
        logger.info(
            "Assign proxy user with ID -> %s to current user; calling -> %s",
            proxy_user_id,
            request_url,
        )
    else:
        post_dict = {}
        if from_date and to_date:
            post_dict["from_date"] = from_date
            post_dict["to_date"] = to_date
        post_dict = {str(proxy_user_id): post_dict}
        post_data = {"add_proxy": json.dumps(post_dict)}
        request_url = self.config()["membersUrl"] + "/proxies"
        logger.info(
            "Assign proxy user with ID -> %s to current user (legacy xGov); calling -> %s",
            proxy_user_id,
            request_url,
        )

    request_header = self.request_form_header()

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.post(
            url=request_url,
            data=post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign proxy user with ID -> %s to current user; status -> %s; error -> %s",
                proxy_user_id,
                response.status_code,
                response.text,
            )
            return None

apply_config(xml_file_path)

Apply Content Server administration settings from XML file

Parameters:

Name Type Description Default
xml_file_path str

name + path of the XML settings file

required

Returns: dict: Import response or None if the import fails. The field response["results"]["data"]["restart"] indicates if the settings require a restart of the OTCS services.

Source code in pyxecm/otcs.py
def apply_config(self, xml_file_path: str) -> dict | None:
    """Apply Content Server administration settings from XML file

    Args:
        xml_file_path (str): name + path of the XML settings file
    Returns:
        dict: Import response or None if the import fails.
              The field response["results"]["data"]["restart"] indicates if the settings
              require a restart of the OTCS services.
    """

    filename = os.path.basename(xml_file_path)

    if not os.path.exists(xml_file_path):
        logger.error(
            "The admin settings file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(xml_file_path),
        )
        return None

    llconfig_file = {
        "file": (filename, open(file=xml_file_path, encoding="utf-8"), "text/xml")
    }

    request_url = self.config()["importSettingsUrl"]
    request_header = self._cookie

    logger.info(
        "Applying admin settings from file -> %s; calling -> %s",
        xml_file_path,
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            files=llconfig_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            logger.debug(
                "Admin settings in file -> %s have been applied", xml_file_path
            )
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import settings file -> %s; status -> %s; error -> %s",
                xml_file_path,
                response.status_code,
                response.text,
            )
            return None

assign_category(node_id, category_id, inheritance=False, apply_to_sub_items=False, apply_action='add_upgrade', add_version=False, clear_existing_categories=False)

Assign a category to a node. Optionally turn on inheritance and apply category to sub-items (if node_id is a container / folder / workspace). If the category is already assigned to the node this method will throw an error.

Parameters:

Name Type Description Default
node_id int

node ID to apply the category to

required
category_id list

ID of the category definition object

required
inheritance bool

turn on inheritance for the category (this makes only sense if the node is a container like a folder or workspace)

False
apply_to_sub_items bool

if True the category is applied to the item and all its sub-items if False the category is only applied to the item

False
apply_action str

supported values are "add", "add_upgrade", "upgrade", "replace", "delete", "none", None

'add_upgrade'
add_version bool

if a document version should be added for the category change (default = False)

False
clear_existing_categories bool

whether or not existing (other) categories should be removed (default = False)

False

Returns: bool: True = success, False = error

Source code in pyxecm/otcs.py
def assign_category(
    self,
    node_id: int,
    category_id: list,
    inheritance: bool = False,
    apply_to_sub_items: bool = False,
    apply_action: str = "add_upgrade",
    add_version: bool = False,
    clear_existing_categories: bool = False,
) -> bool:
    """Assign a category to a node. Optionally turn on inheritance and apply
       category to sub-items (if node_id is a container / folder / workspace).
       If the category is already assigned to the node this method will
       throw an error.

    Args:
        node_id (int): node ID to apply the category to
        category_id (list): ID of the category definition object
        inheritance (bool): turn on inheritance for the category
                               (this makes only sense if the node is a container like a folder or workspace)
        apply_to_sub_items (bool, optional): if True the category is applied to
                                                the item and all its sub-items
                                                if False the category is only applied
                                                to the item
        apply_action (str, optional): supported values are "add", "add_upgrade", "upgrade", "replace", "delete", "none", None
        add_version (bool, optional): if a document version should be added for the category change (default = False)
        clear_existing_categories (bool, optional): whether or not existing (other) categories should be removed (default = False)
    Returns:
        bool: True = success, False = error
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
    request_header = self.request_form_header()

    #
    # 1. Assign Category to Node if not yet assigned:
    #

    existing_category_ids = self.get_node_category_ids(node_id)
    if not category_id in existing_category_ids:
        logger.info(
            "Category with ID -> %s is not yet assigned to node ID -> %s. Assigning it now...",
            str(category_id),
            str(node_id),
        )
        category_post_data = {
            "category_id": category_id,
        }

        logger.info(
            "Assign category with ID -> %s to item with ID -> %s; calling -> %s",
            str(category_id),
            str(node_id),
            request_url,
        )

        retries = 0
        while True:
            response = requests.post(
                url=request_url,
                data=category_post_data,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                break
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to assign category with ID -> %s to node with ID -> %s; status -> %s; error -> %s",
                    str(category_id),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return False

    #
    # 2. Set Inheritance
    #

    request_url_inheritance = request_url + "/" + str(category_id) + "/inheritance"

    retries = 0
    while True:
        if inheritance:
            # Enable inheritance
            response = requests.post(
                url=request_url_inheritance,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
        else:
            # Disable inheritance
            response = requests.delete(
                url=request_url_inheritance,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
        if response.ok:
            break
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to set inheritance for category with ID -> %s on node with ID -> %s; status -> %s; error -> %s",
                str(category_id),
                str(node_id),
                response.status_code,
                response.text,
            )
            return False

    #
    # 3. Apply to sub-items
    #

    if apply_to_sub_items:
        request_url_apply_sub_items = request_url + "/apply"

        category_post_data = {
            "categories": [{"id": category_id, "action": apply_action}],
            "add_version": add_version,
            "clear_existing_categories": clear_existing_categories,
        }

        retries = 0
        while True:
            # we need to wrap the body of this POST call into a "body"
            # tag. This is documented worngly on developer.opentext.com
            response = requests.post(
                url=request_url_apply_sub_items,
                data={"body": json.dumps(category_post_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
            if response.ok:
                break
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to apply category with ID -> %s to sub-items of node with ID -> %s; status -> %s; error -> %s",
                    str(category_id),
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return False
    return True

assign_classification(node_id, classifications, apply_to_sub_items=False)

Assign one or multiple classifications to an Extended ECM item Args: node_id (int): node ID of the Extended ECM item classifications (list): list of classification item IDs apply_to_sub_items (bool, optional): if True the classification is applied to the item and all its sub-items if False the classification is only applied to the item Returns: dict: Response of the request or None if the assignment of the classification has failed.

Source code in pyxecm/otcs.py
def assign_classification(
    self, node_id: int, classifications: list, apply_to_sub_items: bool = False
) -> dict | None:
    """Assign one or multiple classifications to an Extended ECM item
    Args:
        node_id (int): node ID of the Extended ECM item
        classifications (list): list of classification item IDs
        apply_to_sub_items (bool, optional): if True the classification is applied to
                                                the item and all its sub-items
                                                if False the classification is only applied
                                                to the item
    Returns:
        dict: Response of the request or None if the assignment of the classification has failed.
    """

    # the REST API expects a list of dict elements with "id" and the actual IDs
    classification_list = []
    for classification in classifications:
        classification_list.append({"id": classification})

    classification_post_data = {
        "class_id": classification_list,
        "apply_to_sub_items": apply_to_sub_items,
    }

    request_url = (
        self.config()["nodesUrl"] + "/" + str(node_id) + "/classifications"
    )

    request_header = self.request_form_header()

    logger.info(
        "Assign classifications with IDs -> %s to item with ID -> %s; calling -> %s",
        str(classifications),
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=classification_post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign classifications with IDs -> %s to item with ID -> %s; status -> %s; error -> %s",
                str(classifications),
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

assign_item_to_user_group(node_id, subject, instruction, assignees)

Assign an Extended ECM item to users and groups. This is a function used by Extended ECM for Government.

Parameters:

Name Type Description Default
node_id int

node ID of the Extended ECM item (e.g. a workspace or a document)

required
subject str

title / subject of the assignment

required
instructions str

more detailed description or instructions for the assignment

required
assignees list

list of IDs of users or groups

required

Returns: dict: Response of the request or None if the assignment has failed.

Source code in pyxecm/otcs.py
def assign_item_to_user_group(
    self, node_id: int, subject: str, instruction: str, assignees: list
) -> dict | None:
    """Assign an Extended ECM item to users and groups. This is a function used by
       Extended ECM for Government.

    Args:
        node_id (int): node ID of the Extended ECM item (e.g. a workspace or a document)
        subject (str): title / subject of the assignment
        instructions (str): more detailed description or instructions for the assignment
        assignees (list): list of IDs of users or groups
    Returns:
        dict: Response of the request or None if the assignment has failed.
    """

    assignment_post_data = {
        "subject": subject,
        "instruction": instruction,
        "assignees": assignees,
    }

    request_url = (
        self.config()["nodesUrlv2"] + "/" + str(node_id) + "/xgovassignments"
    )

    request_header = self.request_form_header()

    logger.info(
        "Assign item with ID -> %s to assignees -> %s (subject -> %s); calling -> %s",
        str(node_id),
        str(assignees),
        subject,
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "add_assignment" tag.
        response = requests.post(
            url=request_url,
            data={"add_assignment": json.dumps(assignment_post_data)},
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign item with ID -> %s to assignees -> %s (subject -> %s); status -> %s; error -> %s",
                str(node_id),
                str(assignees),
                subject,
                response.status_code,
                response.text,
            )
            return None

assign_permission(node_id, assignee_type, assignee, permissions, apply_to=0)

Assign permissions for Extended ECM item to a user or group.

Parameters:

Name Type Description Default
node_id int

node ID of the Extended ECM item

required
assignee_type str

this can be either "owner", "group" (for owner group), "public", or "custom" (assigned access)

required
assignee int

ID of user or group ("right ID"). If 0 and assigneeType is "owner" or "group" then it is assumed that the owner and owner group should not be changed.

required
permissions list

list of permissions - potential elements: "see" "see_contents" "modify" "edit_attributes" "add_items" "reserve" "add_major_version" "delete_versions" "delete" "edit_permissions"

required
apply_to int

elements to apply permissions to - potential values: 0 = this item (default) 1 = sub-items 2 = This item and sub-items 3 = This item and immediate sub-items

0

Returns: dict: Response of the request or None if the assignment of permissions has failed.

Source code in pyxecm/otcs.py
def assign_permission(
    self,
    node_id: int,
    assignee_type: str,
    assignee: int,
    permissions: list,
    apply_to: int = 0,
) -> dict | None:
    """Assign permissions for Extended ECM item to a user or group.

    Args:
        node_id (int): node ID of the Extended ECM item
        assignee_type (str): this can be either "owner", "group" (for owner group),
                                "public", or "custom" (assigned access)
        assignee (int): ID of user or group ("right ID"). If 0 and assigneeType
                            is "owner" or "group" then it is assumed that the owner and
                            owner group should not be changed.
        permissions (list): list of permissions - potential elements:
                            "see"
                            "see_contents"
                            "modify"
                            "edit_attributes"
                            "add_items"
                            "reserve"
                            "add_major_version"
                            "delete_versions"
                            "delete"
                            "edit_permissions"
        apply_to (int, optional): elements to apply permissions to - potential values:
                             0 = this item (default)
                             1 = sub-items
                             2 = This item and sub-items
                             3 = This item and immediate sub-items
    Returns:
        dict: Response of the request or None if the assignment of permissions has failed.
    """

    if not assignee_type or not assignee_type in [
        "owner",
        "group",
        "public",
        "custom",
    ]:
        logger.error(
            "Missing or wrong assignee type. Needs to be owner, group, public or custom!"
        )
        return None
    if assignee_type == "custom" and not assignee:
        logger.error("Missing permission assignee!")
        return None

    permission_post_data = {
        "permissions": permissions,
        "apply_to": apply_to,
    }

    # Assignees can be specified for owner and group and must be specified for custom:
    #
    if assignee:
        permission_post_data["right_id"] = assignee

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/permissions/"
        + assignee_type
    )

    request_header = self.request_form_header()

    logger.info(
        "Assign permissions -> %s to item with ID -> %s; assignee type -> %s; calling -> %s",
        str(permissions),
        str(node_id),
        assignee_type,
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        if assignee_type == "custom":
            # Custom also has a REST POST - we prefer this one as to
            # also allows to add a new assigned permission (user or group):
            response = requests.post(
                url=request_url,
                data={"body": json.dumps(permission_post_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
        else:
            # Owner, Owner Group and Public require REST PUT:
            response = requests.put(
                url=request_url,
                data={"body": json.dumps(permission_post_data)},
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign permissions -> %s to item with ID -> %s; status -> %s; error -> %s",
                str(permissions),
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

assign_rm_classification(node_id, rm_classification, apply_to_sub_items=False)

Assign a RM classification to an Extended ECM item Args: node_id (int): node ID of the Extended ECM item rm_classification (int): Records Management classification ID apply_to_sub_items (bool, optional): if True the RM classification is applied to the item and all its sub-items if False the RM classification is only applied to the item Returns: dict: Response of the request or None if the assignment of the RM classification has failed.

Source code in pyxecm/otcs.py
def assign_rm_classification(
    self, node_id: int, rm_classification: int, apply_to_sub_items: bool = False
) -> dict | None:
    """Assign a RM classification to an Extended ECM item
    Args:
        node_id (int): node ID of the Extended ECM item
        rm_classification (int): Records Management classification ID
        apply_to_sub_items (bool, optional): if True the RM classification is applied to
                                                the item and all its sub-items
                                                if False the RM classification is only applied
                                                to the item
    Returns:
        dict: Response of the request or None if the assignment of the RM classification has failed.
    """

    rm_classification_post_data = {
        "class_id": rm_classification,
        "apply_to_sub_items": apply_to_sub_items,
    }

    request_url = (
        self.config()["nodesUrl"] + "/" + str(node_id) + "/rmclassifications"
    )

    request_header = self.request_form_header()

    logger.info(
        "Assign RM classifications with ID -> %s to item with ID -> %s; calling -> %s",
        str(rm_classification),
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=rm_classification_post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign RM classifications with ID -> %s to item with ID -> %s; status -> %s; error -> %s",
                str(rm_classification),
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

assign_user_security_clearance(user_id, security_clearance)

Assign a Security Clearance level to an Extended ECM user

Parameters:

Name Type Description Default
user_id int

ID of the user

required
security_clearance int

security clearance level to be set

required

Returns: dict: REST response or None if the REST call fails.

Source code in pyxecm/otcs.py
def assign_user_security_clearance(
    self, user_id: int, security_clearance: int
) -> dict | None:
    """Assign a Security Clearance level to an Extended ECM user

    Args:
        user_id (int): ID of the user
        security_clearance (int): security clearance level to be set
    Returns:
        dict: REST response or None if the REST call fails.
    """

    assign_user_security_clearance_post_data = {
        "securityLevel": security_clearance,
    }

    request_url = self.config()[
        "userSecurityUrl"
    ] + "/{}/securityclearancelevel".format(user_id)
    request_header = self.request_form_header()

    logger.info(
        "Assign security clearance -> %s to user with ID -> %s; calling -> %s",
        str(security_clearance),
        str(user_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=assign_user_security_clearance_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign security clearance -> %s to user with ID -> %s; status -> %s; error -> %s",
                str(security_clearance),
                str(user_id),
                response.status_code,
                response.text,
            )
            return None

assign_user_supplemental_markings(user_id, supplemental_markings)

Assign a list of Supplemental Markings to a user

Parameters:

Name Type Description Default
user_id int

ID of the user

required
supplemental_markings list of strings

list of Supplemental Markings to be set

required

Returns: dict: REST response or None if the REST call fails.

Source code in pyxecm/otcs.py
def assign_user_supplemental_markings(
    self, user_id: int, supplemental_markings: list
) -> dict | None:
    """Assign a list of Supplemental Markings to a user

    Args:
        user_id (int): ID of the user
        supplemental_markings (list of strings): list of Supplemental Markings to be set
    Returns:
        dict: REST response or None if the REST call fails.
    """

    assign_user_supplemental_markings_post_data = {
        "suppMarks": supplemental_markings,
    }

    request_url = self.config()[
        "userSecurityUrl"
    ] + "/{}/supplementalmarkings".format(user_id)
    request_header = self.request_form_header()

    logger.info(
        "Assign supplemental markings -> %s to user with ID -> %s; calling -> %s",
        str(supplemental_markings),
        str(user_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=assign_user_supplemental_markings_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to assign supplemental markings -> %s to user with ID -> %s; status -> %s; error -> %s",
                str(supplemental_markings),
                str(user_id),
                response.status_code,
                response.text,
            )
            return None

assign_workspace_permissions(workspace_id, role_id, permissions, apply_to=2)

Update permissions of a workspace role Args: workspace_id (int): ID of the workspace role_id (int): ID of the role permissions (list): List of permissions - potential elements: "see" "see_contents" "modify" "edit_attributes" "add_items" "reserve" "add_major_version" "delete_versions" "delete" "edit_permissions" apply_to (int, optional): Items to apply the permission change. Possible values: 0 = this item 1 = sub-items 2 = This item and sub-items (default) 3 = This item and immediate sub-items Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def assign_workspace_permissions(
    self, workspace_id: int, role_id: int, permissions: list, apply_to: int = 2
) -> dict | None:
    """Update permissions of a workspace role
    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        permissions (list): List of permissions - potential elements:
                            "see"
                            "see_contents"
                            "modify"
                            "edit_attributes"
                            "add_items"
                            "reserve"
                            "add_major_version"
                            "delete_versions"
                            "delete"
                            "edit_permissions"
        apply_to (int, optional):  Items to apply the permission change. Possible values:
                                   0 = this item
                                   1 = sub-items
                                   2 = This item and sub-items (default)
                                   3 = This item and immediate sub-items
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    request_url = self.config()["businessWorkspacesUrl"] + "/{}/roles/{}".format(
        workspace_id, role_id
    )

    request_header = self.request_form_header()

    logger.info(
        "Updating Permissions of role with ID -> %s of workspace with ID -> %s with permissions -> %s; calling -> %s",
        str(role_id),
        str(workspace_id),
        str(permissions),
        request_url,
    )

    permission_post_data = {
        "permissions": permissions,
        "apply_to": apply_to,
    }

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            headers=request_header,
            data={"body": json.dumps(permission_post_data)},
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update permissions for role with ID -> %s of workspace with ID -> %s; status -> %s; error -> %s",
                str(role_id),
                str(workspace_id),
                response.status_code,
                response.text,
            )
            return None

authenticate(revalidate=False)

Authenticates at Content Server and retrieve OTCS Ticket.

Parameters:

Name Type Description Default
revalidate bool

determinse if a re-athentication is enforced (e.g. if session has timed out with 401 error) By default we use the OTDS ticket (if exists) for the authentication with OTCS. This switch allows the forced usage of username / password for the authentication.

False

Returns: dict: Cookie information of None in case of an error. Also stores cookie information in self._cookie

Source code in pyxecm/otcs.py
def authenticate(self, revalidate: bool = False) -> dict | None:
    """Authenticates at Content Server and retrieve OTCS Ticket.

    Args:
        revalidate (bool, optional): determinse if a re-athentication is enforced
                                     (e.g. if session has timed out with 401 error)
                                     By default we use the OTDS ticket (if exists) for the authentication with OTCS.
                                     This switch allows the forced usage of username / password for the authentication.
    Returns:
        dict: Cookie information of None in case of an error.
              Also stores cookie information in self._cookie
    """

    # Already authenticated and session still valid?
    if self._cookie and not revalidate:
        logger.info(
            "Session still valid - return existing cookie -> %s",
            str(self._cookie),
        )
        return self._cookie

    otcs_ticket = None

    logger.info("Wait for OTCS to be ready...")
    while not self.is_ready():
        logger.warning(
            "OTCS is not ready to receive requests yet. Waiting 30 seconds..."
        )
        time.sleep(30)

    request_url = self.config()["authenticationUrl"]

    if self._otds_ticket and not revalidate:
        logger.info(
            "Requesting OTCS ticket with OTDS ticket; calling -> %s",
            request_url,
        )
        request_header = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
            "OTDSTicket": self._otds_ticket,
        }

        try:
            response = requests.get(
                url=request_url, headers=request_header, timeout=10
            )
            if response.ok:
                otcs_ticket = response.headers.get("OTCSTicket")

        except requests.exceptions.RequestException as exception:
            logger.warning(
                "Unable to connect to -> %s; error -> %s",
                request_url,
                exception.strerror,
            )

    # Check if previous authentication was not successful.
    # Then we do the normal username + password authentication:
    if not otcs_ticket:
        logger.info(
            "Requesting OTCS ticket with User/Password; calling -> %s",
            request_url,
        )

        response = None
        try:
            response = requests.post(
                url=request_url,
                data=self.credentials(),  # this includes username + password
                headers=REQUEST_FORM_HEADERS,
                timeout=REQUEST_TIMEOUT,
            )
        except requests.exceptions.RequestException as exception:
            logger.warning(
                "Unable to connect to -> %s; error -> %s",
                request_url,
                exception.strerror,
            )
            logger.warning("OTCS service may not be ready yet.")
            return None

        if response.ok:
            authenticate_dict = self.parse_request_response(
                response, "This can be normal during restart", False
            )
            if not authenticate_dict:
                return None
            else:
                otcs_ticket = authenticate_dict["ticket"]
                logger.info("Ticket -> %s", otcs_ticket)
        else:
            logger.error(
                "Failed to request an OTCS ticket; error -> %s", response.text
            )
            return None

    # Store authentication ticket:
    self._cookie = {"otcsticket": otcs_ticket, "LLCookie": otcs_ticket}
    self._otcs_ticket = otcs_ticket

    return self._cookie

base_url()

Returns the base URL of Extended ECM

Returns:

Name Type Description
str str

base URL

Source code in pyxecm/otcs.py
def base_url(self) -> str:
    """Returns the base URL of Extended ECM

    Returns:
        str: base URL
    """
    return self.config()["baseUrl"]

check_node_name(parent_id, node_name)

Check if a node with a given name does already exist under a given parent node.

Parameters:

Name Type Description Default
parent_id int

ID of the parent location

required
node_name str

name of the new node

required

Returns: dict | None: if response["results"] contains an element then the node with the name does exist. if not response["results"] then the node with the given name does not exist None in case an error occured

Source code in pyxecm/otcs.py
def check_node_name(self, parent_id: int, node_name: str) -> dict | None:
    """Check if a node with a given name does already exist under a given parent node.

    Args:
        parent_id (int): ID of the parent location
        node_name (str): name of the new node
    Returns:
        dict | None: if response["results"] contains an element then the node with the name does exist.
                     if not response["results"] then the node with the given name does not exist
                     None in case an error occured
    """

    request_url = self.config()["validationUrl"]
    request_header = self.request_form_header()

    logger.info(
        "Check if node with name -> %s can be created in parent with ID -> %s; calling -> %s",
        node_name,
        str(parent_id),
        request_url,
    )

    check_node_name_post_data = {"parent_id": parent_id, "names": [node_name]}

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data={"body": json.dumps(check_node_name_post_data)},
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to check if node name -> %s can be created in parent with ID -> %s; status -> %s; error -> %s",
                node_name,
                str(parent_id),
                response.status_code,
                response.text,
            )
            return None

check_workspace_aviator(workspace_id)

Check if Content Aviator is enabled for a workspace

Parameters:

Name Type Description Default
workspace_id int

node ID of the workspace

required

Returns: bool: True if aviator is enabled, False otherwise

Source code in pyxecm/otcs.py
def check_workspace_aviator(
    self,
    workspace_id: int,
) -> bool:
    """Check if Content Aviator is enabled for a workspace

    Args:
        workspace_id (int): node ID of the workspace
    Returns:
        bool: True if aviator is enabled, False otherwise
    """

    response = self.get_node_actions(
        node_id=workspace_id, filter_actions=["disableai", "enableai"]
    )
    result_data = self.get_result_value(
        response=response,
        key=str(workspace_id),
    )
    if result_data and "data" in result_data:
        data = result_data["data"]
        if "disableai" in data:
            logger.info(
                "Aviator is enabled for workspace with ID -> %s", str(workspace_id)
            )
            return True
        elif "enableai" in data:
            logger.info(
                "Aviator is disabled for workspace with ID -> %s", str(workspace_id)
            )

    return False

config()

Returns the configuration dictionary

Returns:

Name Type Description
dict dict

Configuration dictionary

Source code in pyxecm/otcs.py
def config(self) -> dict:
    """Returns the configuration dictionary

    Returns:
        dict: Configuration dictionary
    """
    return self._config

convert_permission_string_to_permission_value(permissions)

Converts a list of permission names (strongs) to a bit-mask.

Parameters:

Name Type Description Default
permissions list

List of permission names - see conversion variable below.

required

Returns: int: bit-encoded permission value

Source code in pyxecm/otcs.py
def convert_permission_string_to_permission_value(self, permissions: list) -> int:
    """Converts a list of permission names (strongs) to a bit-mask.

    Args:
        permissions (list): List of permission names - see conversion variable below.
    Returns:
        int: bit-encoded permission value
    """

    conversion = {
        "see": 130,  # Bits 2 and 8
        "see_contents": 36865,  # Bit 17
        "modify": 65536,  # Bit 18
        "edit_attributes": 131072,  # Bit 19
        "add_items": 4,  # Bit 3
        "reserve": 8192,  # Bit 14
        "add_major_version": 4194304,  # Bit 23
        "delete_versions": 16384,  # Bit 15
        "delete": 8,  # Bit 4
        "edit_permissions": 16,  # Bit 5
    }

    permission_value = 0

    for permission in permissions:
        if not conversion.get(permission):
            logger.error("Illegal permission value -> %s", str(permission))
            return 0
        permission_value += conversion[permission]

    return permission_value

convert_permission_value_to_permission_string(permission_value)

Converts a bit-encoded permission value to a list of permission names (strings).

Parameters:

Name Type Description Default
permission_value int

bit-encoded permission value

required

Returns: list: list of permission names

Source code in pyxecm/otcs.py
def convert_permission_value_to_permission_string(
    self, permission_value: int
) -> list:
    """Converts a bit-encoded permission value to a list of permission names (strings).

    Args:
        permission_value (int): bit-encoded permission value
    Returns:
        list: list of permission names
    """

    conversion = {
        "see": 130,  # Bits 2 and 8
        "see_contents": 36865,  # Bit 17
        "modify": 65536,  # Bit 18
        "edit_attributes": 131072,  # Bit 19
        "add_items": 4,  # Bit 3
        "reserve": 8192,  # Bit 14
        "add_major_version": 4194304,  # Bit 23
        "delete_versions": 16384,  # Bit 15
        "delete": 8,  # Bit 4
        "edit_permissions": 16,  # Bit 5
    }

    permissions = []

    for key, value in conversion.items():
        if permission_value & value:  # binary and
            permissions.append(key)

    return permissions

cookie()

Returns the login cookie of Extended ECM. This is set by the authenticate() method

Returns:

Name Type Description
dict dict

Estended ECM cookie

Source code in pyxecm/otcs.py
def cookie(self) -> dict:
    """Returns the login cookie of Extended ECM.
       This is set by the authenticate() method

    Returns:
        dict: Estended ECM cookie
    """
    return self._cookie

create_document_from_template(template_id, parent_id, classification_id, category_data, doc_name, doc_desciption='')

Create a document based on a document template

Parameters:

Name Type Description Default
template_id int

node ID of the document template

required
parent_id int

node ID of the target location (parent)

required
classification_id int

node ID of the classification

required
category_data dict

metadata / category data Example: category ID = 12508 { "12508": { "12508_2": "Draft", # Text drop-down "12508_3": 8559, # user ID "12508_4": "2023-05-10", # date "12508_6": 7357, # user ID "12508_7": "2023-05-11", # date "12508_5": True, # checkbox / bool "12508_8": "EN", # text drop-down "12508_9": "MS Word", # text drop-down } }

required
doc_name str

Name of the item to create.

required
doc_description str

Description of the item to create.

required
Source code in pyxecm/otcs.py
def create_document_from_template(
    self,
    template_id: int,
    parent_id: int,
    classification_id: int,
    category_data: dict,
    doc_name: str,
    doc_desciption: str = "",
) -> dict | None:
    """Create a document based on a document template

    Args:
        template_id (int): node ID of the document template
        parent_id (int): node ID of the target location (parent)
        classification_id (int): node ID of the classification
        category_data (dict): metadata / category data
                                Example: category ID = 12508
                                {
                                    "12508": {
                                        "12508_2": "Draft",         # Text drop-down
                                        "12508_3": 8559,            # user ID
                                        "12508_4": "2023-05-10",    # date
                                        "12508_6": 7357,            # user ID
                                        "12508_7": "2023-05-11",    # date
                                        "12508_5": True,            # checkbox / bool
                                        "12508_8": "EN",            # text drop-down
                                        "12508_9": "MS Word",       # text drop-down
                                    }
                                }
        doc_name (str): Name of the item to create.
        doc_description (str, optional): Description of the item to create.
    """

    create_document_post_data = {
        "template_id": template_id,
        "parent_id": parent_id,
        "name": doc_name,
        "description": doc_desciption,
        "type": 144,
        "roles": {
            "categories": category_data,
            "classifications": {"create_id": [classification_id], "id": []},
        },
    }

    request_url = self.config()["doctemplatesUrl"]
    request_header = self.request_form_header()

    logger.info(
        "Create document -> %s from template with ID -> %s in target location -> %s (parent ID) with classification ID -> %s; calling -> %s",
        doc_name,
        str(template_id),
        str(parent_id),
        str(classification_id),
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.post(
            url=request_url,
            # this seems to only work with a "body" tag and is different form the documentation
            # on developer.opentext.com
            data={"body": json.dumps(create_document_post_data)},
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create document -> %s; status -> %s; error -> %s",
                doc_name,
                response.status_code,
                response.text,
            )
            return None

create_item(parent_id, item_type, item_name, item_description='', url='', original_id=0)

Create an Extended ECM item. This REST call is somewhat limited. It cannot set favortie (featured item) or hidden item. It does also not accept owner group information.

Parameters:

Name Type Description Default
parent_id int

Node ID of the parent

required
item_type str

Type of the item (e.g. 0 = foler, 140 = URL)

required
item_name str

Name of the item

required
item_description str

Description of the item

''
url str

Address of the URL item (if it is an URL item type)

''
original_id int

Node ID of the original (referenced) item. Required if a shortcut item is created

0

Returns: dict: Request response of the create item call or None if the REST call has failed.

Source code in pyxecm/otcs.py
def create_item(
    self,
    parent_id: int,
    item_type: str,
    item_name: str,
    item_description: str = "",
    url: str = "",
    original_id: int = 0,
) -> dict | None:
    """Create an Extended ECM item. This REST call is somewhat limited. It cannot set favortie (featured item) or hidden item.
       It does also not accept owner group information.

    Args:
        parent_id (int): Node ID of the parent
        item_type (str): Type of the item (e.g. 0 = foler, 140 = URL)
        item_name (str): Name of the item
        item_description (str, optional): Description of the item
        url (str, optional): Address of the URL item (if it is an URL item type)
        original_id (int, optional): Node ID of the original (referenced) item.
                                     Required if a shortcut item is created
    Returns:
        dict: Request response of the create item call or None if the REST call has failed.
    """

    create_item_post_data = {
        "parent_id": parent_id,
        "type": item_type,
        "name": item_name,
        "description": item_description,
    }

    if url:
        create_item_post_data["url"] = url
    if original_id > 0:
        create_item_post_data["original_id"] = original_id

    request_url = self.config()["nodesUrlv2"]
    request_header = self.request_form_header()

    logger.info(
        "Create item -> %s (type -> %s) under parent with ID -> %s; calling -> %s",
        item_name,
        item_type,
        str(parent_id),
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.post(
            url=request_url,
            data={"body": json.dumps(create_item_post_data)},
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create item -> %s; status -> %s; error -> %s",
                item_name,
                response.status_code,
                response.text,
            )
            return None

create_records_management_hold(hold_type, name, comment, alternate_id='', parent_id=0, date_applied='', date_to_remove='')

Create a new Records Management Hold.

Parameters:

Name Type Description Default
hold_type str

type of the Hold

required
name str

name of the RSI

required
comment str

comment

required
alternate_id str

alternate hold ID

''
parent_id int

ID of the parent node. If parent_id is 0 the item will be created right under "Hold Management" (top level item)

0
date_applied str

create date of the Hold in this format: YYYY-MM-DDTHH:mm:ss

''
date_to_remove str

suspend date of the Hold in this format: YYYY-MM-DDTHH:mm:ss

''

Returns: dict: Hold data or None if the request fails. The dict structure is this: {'holdID': }

Source code in pyxecm/otcs.py
def create_records_management_hold(
    self,
    hold_type: str,
    name: str,
    comment: str,
    alternate_id: str = "",
    parent_id: int = 0,
    date_applied: str = "",
    date_to_remove: str = "",
) -> dict | None:
    """Create a new Records Management Hold.

    Args:
        hold_type (str): type of the Hold
        name (str): name of the RSI
        comment (str): comment
        alternate_id (str, optional): alternate hold ID
        parent_id (int, optional): ID of the parent node. If parent_id is 0 the item will be created right under "Hold Management" (top level item)
        date_applied (str, optional): create date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
        date_to_remove (str, optional): suspend date of the Hold in this format: YYYY-MM-DDTHH:mm:ss
    Returns:
        dict: Hold data or None if the request fails. The dict structure is this: {'holdID': <ID>}
    """

    if date_applied == "":
        now = datetime.now()
        date_applied = now.strftime("%Y-%m-%dT%H:%M:%S")

    create_hold_post_data = {
        "type": hold_type,
        "name": name,
        "comment": comment,
        "date_applied": date_applied,
        "date_to_remove": date_to_remove,
        "alternate_id": alternate_id,
    }

    if parent_id > 0:
        create_hold_post_data["parent_id"] = parent_id

    request_url = self.config()["holdsUrl"]

    request_header = self.request_form_header()

    logger.info(
        "Create Records Management Hold -> %s; calling -> %s", name, request_url
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=create_hold_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create Records Management Hold -> %s; status -> %s; error -> %s",
                name,
                response.status_code,
                response.text,
            )
            return None

create_records_management_rsi(name, status, status_date, description, subject, title, dispcontrol)

Create a new Records Management RSI.

Parameters:

Name Type Description Default
name str

name of the RSI

required
status str

status of the RSI

required
status_date str

statusDate of the RSI YYYY-MM-DDTHH:mm:ss

required
description str

description of the RSI

required
subject str

status of the RSI

required
title str

status of the RSI

required
dispcontrol bool

status of the RSI

required

Returns: dict: RSI data or None if the request fails.

Source code in pyxecm/otcs.py
def create_records_management_rsi(
    self,
    name: str,
    status: str,
    status_date: str,
    description: str,
    subject: str,
    title: str,
    dispcontrol: bool,
) -> dict | None:
    """Create a new Records Management RSI.

    Args:
        name (str): name of the RSI
        status (str): status of the RSI
        status_date (str): statusDate of the RSI YYYY-MM-DDTHH:mm:ss
        description (str): description of the RSI
        subject (str): status of the RSI
        title (str): status of the RSI
        dispcontrol (bool): status of the RSI
    Returns:
        dict: RSI data or None if the request fails.
    """

    if status_date == "":
        now = datetime.now()
        status_date = now.strftime("%Y-%m-%dT%H:%M:%S")

    create_rsi_post_data = {
        "name": name,
        "status": status,
        "statusDate": status_date,
        "description": description,
        "subject": subject,
        "title": title,
        "dispcontrol": dispcontrol,
    }

    request_url = self.config()["rsiSchedulesUrl"]

    request_header = self.request_form_header()

    logger.info(
        "Create Records Management RSI -> %s; calling -> %s", name, request_url
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=create_rsi_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create Records Management RSI -> %s; status -> %s; error -> %s",
                name,
                response.status_code,
                response.text,
            )
            return None

create_records_management_rsi_schedule(rsi_id, stage, event_type=1, object_type='LIV', rule_code='', rule_comment='', date_to_use=91, retention_years=0, retention_months=0, retention_days=0, category_id=0, attribute_id=0, year_end_month=12, year_end_day=31, retention_intervals=1, fixed_retention=True, maximum_retention=True, fixed_date='', event_condition='', disposition='', action_code=0, description='', new_status='', min_num_versions_to_keep=1, purge_superseded=False, purge_majors=False, mark_official_rendition=False)

Create a new Records Management RSI Schedule for an existing RSI.

Parameters:

Name Type Description Default
rsi_id int

ID of an existing RSI the schedule should be created for

required
stage str

retention stage - this is the key parameter to define multiple stages (stages are basically schedules)

required
event_type int

1 Calculated Date, 2 Calendar Calculation, 3 Event Based, 4 Fixed Date, 5 Permanent

1
object_type str

either "LIV" - Classified Objects (default) or "LRM" - RM Classifications

'LIV'
rule_code str

rule code - this value must be defined upfront

''
rule_comment str

comment for the rule

''
date_to_use int

91 Create Date, 92 Reserved Data, 93 Modification Date, 94 Status Date, 95 Records Date

91
retention_years int

years to wait before disposition

0
retention_months int

month to wait before disposition

0
retention_days int

days to wait before disposition

0
category_id int

ID of the category

0
attribute_id int

ID of the category attribute

0
year_end_month int

month the year ends (default = 12)

12
year_end_day int

day the year ends (default = 31)

31
retention_intervals int

retention intervals

1
fixed_retention bool

fixedRetention

True
maximum_retention (bool, optional)

maximumRetention

True
fixed_date(str, optional

fixed date format : YYYY-MM-DDTHH:mm:ss

required
event_condition str

eventCondition

''
disposition str

disposition

''
action_code int

0 None, 1 Change Status, 7 Close, 8 Finalize Record, 9 Mark Official, 10 Export, 11 Update Storage Provider, 12 Delete Electronic Format, 15 Purge Versions, 16 Make Rendition, 32 Destroy

0
description str

description

''
new_status str

new status

''
min_num_versions_to_keep int

minimum document versions to keep, . Default is 1.

1
purge_superseded bool

purge superseded. Default is False.

False
purge_majors bool

purge majors. Default is False.

False
mark_official_rendition bool

mark official rendition. Default is False.

False

Returns: dict: RSI Schedule data or None if the request fails.

Source code in pyxecm/otcs.py
def create_records_management_rsi_schedule(
    self,
    rsi_id: int,
    stage: str,
    event_type: int = 1,
    object_type: str = "LIV",
    rule_code: str = "",
    rule_comment: str = "",
    date_to_use: int = 91,
    retention_years: int = 0,
    retention_months: int = 0,
    retention_days: int = 0,
    category_id: int = 0,
    attribute_id: int = 0,
    year_end_month: int = 12,
    year_end_day: int = 31,
    retention_intervals: int = 1,
    fixed_retention: bool = True,
    maximum_retention: bool = True,
    fixed_date: str = "",
    event_condition: str = "",
    disposition: str = "",
    action_code: int = 0,
    description: str = "",
    new_status: str = "",
    min_num_versions_to_keep: int = 1,
    purge_superseded: bool = False,
    purge_majors: bool = False,
    mark_official_rendition: bool = False,
) -> dict | None:
    """Create a new Records Management RSI Schedule for an existing RSI.

    Args:
        rsi_id (int): ID of an existing RSI the schedule should be created for
        stage (str): retention stage - this is the key parameter to define multiple stages (stages are basically schedules)
        event_type (int): 1 Calculated Date, 2 Calendar Calculation, 3 Event Based, 4 Fixed Date, 5 Permanent
        object_type (str): either "LIV" - Classified Objects (default) or "LRM" - RM Classifications
        rule_code (str, optional): rule code - this value must be defined upfront
        rule_comment (str, optional): comment for the rule
        date_to_use (int, optional): 91 Create Date, 92 Reserved Data, 93 Modification Date, 94 Status Date, 95 Records Date
        retention_years (int, optional): years to wait before disposition
        retention_months (int, optional): month to wait before disposition
        retention_days (int, optional): days to wait before disposition
        category_id (int, optional): ID of the category
        attribute_id (int, optional): ID of the category attribute
        year_end_month (int, optional): month the year ends (default = 12)
        year_end_day (int, optional): day the year ends (default = 31)
        retention_intervals (int, optional): retention intervals
        fixed_retention (bool, optional): fixedRetention
        maximum_retention (bool,optional): maximumRetention
        fixed_date(str, optional): fixed date format : YYYY-MM-DDTHH:mm:ss
        event_condition (str, optional): eventCondition
        disposition (str, optional): disposition
        action_code (int, optional): 0 None, 1 Change Status, 7 Close, 8 Finalize Record, 9 Mark Official, 10 Export, 11 Update Storage Provider, 12 Delete Electronic Format, 15 Purge Versions, 16 Make Rendition, 32 Destroy
        description (str, optional): description
        new_status (str, optional): new status
        min_num_versions_to_keep (int, optional): minimum document versions to keep, . Default is 1.
        purge_superseded (bool, optional): purge superseded. Default is False.
        purge_majors (bool, optional): purge majors. Default is False.
        mark_official_rendition (bool, optional): mark official rendition. Default is False.
    Returns:
        dict: RSI Schedule data or None if the request fails.
    """

    if fixedDate == "":
        now = datetime.now()
        fixedDate = now.strftime("%Y-%m-%dT%H:%M:%S")

    create_rsi_schedule_post_data = {
        "objectType": object_type,
        "stage": stage,
        "eventType": event_type,
        "ruleCode": rule_code,
        "ruleComment": rule_comment,
        "dateToUse": date_to_use,
        "retentionYears": retention_years,
        "retentionMonths": retention_months,
        "retentionDays": retention_days,
        "categoryId": category_id,
        "attributeId": attribute_id,
        "yearEndMonth": year_end_month,
        "yearEndDay": year_end_day,
        "retentionIntervals": retention_intervals,
        "fixedRetention": fixed_retention,
        "maximumRetention": maximum_retention,
        "fixedDate": fixed_date,
        "eventCondition": event_condition,
        "disposition": disposition,
        "actionCode": action_code,
        "description": description,
        "newStatus": new_status,
        "minNumVersionsToKeep": min_num_versions_to_keep,
        "purgeSuperseded": purge_superseded,
        "purgeMajors": purge_majors,
        "markOfficialRendition": mark_official_rendition,
    }

    request_url = self.config()["rsiSchedulesUrl"] + "/" + str(rsi_id) + "/stages"

    request_header = self.request_form_header()

    logger.info(
        "Create Records Management RSI Schedule -> %s for RSI -> %s; calling -> %s",
        stage,
        str(rsi_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=create_rsi_schedule_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create Records Management RSI Schedule -> %s; status -> %s; error -> %s",
                stage,
                response.status_code,
                response.text,
            )
            return None

create_transport_workbench(workbench_name)

Create a Workbench in the Transport Volume.

Parameters:

Name Type Description Default
workbench_name str

Name of the workbench to be created

required

Returns: dict: Create response or None if the creation fails.

Source code in pyxecm/otcs.py
def create_transport_workbench(self, workbench_name: str) -> dict | None:
    """Create a Workbench in the Transport Volume.

    Args:
        workbench_name (str): Name of the workbench to be created
    Returns:
        dict: Create response or None if the creation fails.
    """

    create_worbench_post_data = {"type": "528", "name": workbench_name}

    request_url = self.config()["nodesUrlv2"]
    request_header = self.request_form_header()

    logger.info(
        "Create transport workbench -> %s; calling -> %s",
        workbench_name,
        request_url,
    )
    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=create_worbench_post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create transport workbench -> %s; status -> %s; error -> %s",
                workbench_name,
                response.status_code,
                response.text,
            )
            return None

create_workspace(workspace_template_id, workspace_name, workspace_description, workspace_type, category_data=None, external_system_id=None, bo_type=None, bo_id=None, parent_id=None, ibo_workspace_id=None, show_error=True)

Create a new business workspace.

Parameters:

Name Type Description Default
workspace_template_id int

ID of the workspace template

required
workspace_name str

Name of the workspace

required
workspace_description str

Description of the workspace

required
workspace_type int

Type ID of the workspace

required
category_data dict

Category and attributes

None
external_system_id str

Identifier of the external system (None if no external system)

None
bo_type str

Business object type (None if no external system)

None
bo_id str

Business object identifier / key (None if no external system)

None
parent_id str

Parent ID of the workspaces. Needs only be specified in special cases where workspace location cannot be derived from workspace type definition

None
ibo_workspace_id int

Node ID of an existing workspace that is already connected to another external system. This allows for subsequent calls to coonect the workspace to multiple Business Objects (IBO = Identical Business Objects)

None
show_error bool

Log an error if workspace cration fails. Otherwise log a warning.

True

Returns: dict: Workspace Create Form data or None if the request fails.

Source code in pyxecm/otcs.py
def create_workspace(
    self,
    workspace_template_id: int,
    workspace_name: str,
    workspace_description: str,
    workspace_type: int,
    category_data: dict | None = None,
    external_system_id: int = None,
    bo_type: int | None = None,
    bo_id: int | None = None,
    parent_id: int | None = None,
    ibo_workspace_id: int | None = None,
    show_error: bool = True,
) -> dict | None:
    """Create a new business workspace.

    Args:
        workspace_template_id (int): ID of the workspace template
        workspace_name (str): Name of the workspace
        workspace_description (str): Description of the workspace
        workspace_type (int): Type ID of the workspace
        category_data (dict): Category and attributes
        external_system_id (str, optional): Identifier of the external system (None if no external system)
        bo_type (str, optional): Business object type (None if no external system)
        bo_id (str, optional): Business object identifier / key (None if no external system)
        parent_id (str, optional): Parent ID of the workspaces. Needs only be specified in special
                                   cases where workspace location cannot be derived from workspace
                                   type definition
        ibo_workspace_id (int, optional): Node ID of an existing workspace that is already connected to another
                                          external system. This allows for subsequent calls to coonect the workspace
                                          to multiple Business Objects (IBO = Identical Business Objects)
        show_error (bool, optional): Log an error if workspace cration fails. Otherwise log a warning.
    Returns:
        dict: Workspace Create Form data or None if the request fails.
    """

    # Avoid linter warning W0102
    if category_data is None:
        category_data = {}

    create_workspace_post_data = {
        "template_id": str(workspace_template_id),
        "name": workspace_name,
        "description": workspace_description,
        "wksp_type_id": str(workspace_type),
        "type": str(848),
        "roles": category_data,
    }

    # Is this workspace connected to a business application / external system?
    if external_system_id and bo_type and bo_id:
        create_workspace_post_data["ext_system_id"] = str(external_system_id)
        create_workspace_post_data["bo_type"] = str(bo_type)
        create_workspace_post_data["bo_id"] = str(bo_id)
        logger.info(
            "Use business object connection -> (%s, %s, %s) for workspace -> %s",
            str(external_system_id),
            str(bo_type),
            str(bo_id),
            workspace_name,
        )
        if ibo_workspace_id:
            logger.info(
                "This is a subsequent call to create a cross-application workspace (IBO)"
            )
            create_workspace_post_data["ibo_workspace_id"] = ibo_workspace_id

    # If workspace creation location cannot be derived from the workspace type
    # there may be an optional parent parameter passed to this method. This can
    # also be the case if workspaces are nested into each other:
    if parent_id is not None:
        create_workspace_post_data["parent_id"] = parent_id
        logger.info(
            "Use specified location -> %s for workspace -> %s",
            str(parent_id),
            workspace_name,
        )
    else:
        logger.info(
            "Determine location of workspace -> %s via workspace type -> %s",
            workspace_name,
            str(workspace_type),
        )

    request_url = self.config()["businessWorkspacesUrl"]
    request_header = self.request_form_header()

    logger.info(
        "Create workspace -> %s with type -> %s from template -> %s; calling -> %s",
        workspace_name,
        str(workspace_type),
        str(workspace_template_id),
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        # See https://developer.opentext.com/apis/14ba85a7-4693-48d3-8c93-9214c663edd2/4403207c-40f1-476a-b794-fdb563e37e1f/07229613-7ef4-4519-8b8a-47eaff639d42#operation/createBusinessWorkspace
        response = requests.post(
            url=request_url,
            headers=request_header,
            data={"body": json.dumps(create_workspace_post_data)},
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to create workspace -> %s from template with ID -> %s; status -> %s; error -> %s",
                    workspace_name,
                    str(workspace_template_id),
                    response.status_code,
                    response.text,
                )
            else:
                logger.warning(
                    "Couldn't create workspace -> %s from template with ID -> %s (it may exist already); status -> %s; error -> %s",
                    workspace_name,
                    str(workspace_template_id),
                    response.status_code,
                    response.text,
                )
            return None

create_workspace_relationship(workspace_id, related_workspace_id, relationship_type='child')

Create a relationship between two workspaces.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
related_workspace_id int

ID of the related workspace

required
relationship_type str

"parent" or "child" - "child" is default if omitted

'child'

Returns: dict: Workspace Relationship data (json) or None if the request fails.

Source code in pyxecm/otcs.py
def create_workspace_relationship(
    self,
    workspace_id: int,
    related_workspace_id: int,
    relationship_type: str = "child",
) -> dict | None:
    """Create a relationship between two workspaces.

    Args:
        workspace_id (int): ID of the workspace
        related_workspace_id (int): ID of the related workspace
        relationship_type (str, optional): "parent" or "child" - "child" is default if omitted
    Returns:
        dict: Workspace Relationship data (json) or None if the request fails.
    """

    create_workspace_relationship_post_data = {
        "rel_bw_id": str(related_workspace_id),
        "rel_type": relationship_type,
    }

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/relateditems".format(workspace_id)
    request_header = self.request_form_header()

    logger.info(
        "Create workspace relationship between -> %s and -> %s; calling -> %s",
        str(workspace_id),
        str(related_workspace_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=create_workspace_relationship_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to create workspace relationship between -> %s and -> %s; status -> %s; error -> %s",
                str(workspace_id),
                str(related_workspace_id),
                response.status_code,
                response.text,
            )
            return None

credentials()

Get credentials (username + password)

Returns:

Name Type Description
dict dict

dictionary with username and password

Source code in pyxecm/otcs.py
def credentials(self) -> dict:
    """Get credentials (username + password)

    Returns:
        dict: dictionary with username and password
    """
    return {
        "username": self.config()["username"],
        "password": self.config()["password"],
    }

cs_public_url()

Returns the public (external) Extended ECM URL (incl. base_path /cs/cs )

Returns:

Name Type Description
str str

Extended ECM Public URL

Source code in pyxecm/otcs.py
def cs_public_url(self) -> str:
    """Returns the public (external) Extended ECM URL (incl. base_path /cs/cs )

    Returns:
        str: Extended ECM Public URL
    """
    return self.config()["csPublicUrl"]

cs_support_public_url()

Returns the Extended ECM Public Support URL

Returns:

Name Type Description
str str

Extended ECM Public Support URL

Source code in pyxecm/otcs.py
def cs_support_public_url(self) -> str:
    """Returns the Extended ECM Public Support URL

    Returns:
        str: Extended ECM Public Support URL
    """
    return self.config()["supportPublicUrl"]

cs_support_url()

Returns the Extended ECM Support URL

Returns:

Name Type Description
str str

Extended ECM Support URL

Source code in pyxecm/otcs.py
def cs_support_url(self) -> str:
    """Returns the Extended ECM Support URL

    Returns:
        str: Extended ECM Support URL
    """
    return self.config()["supportUrl"]

cs_url()

Returns the Extended ECM URL

Returns:

Name Type Description
str str

Extended ECM URL

Source code in pyxecm/otcs.py
def cs_url(self) -> str:
    """Returns the Extended ECM URL

    Returns:
        str: Extended ECM URL
    """
    return self.config()["csUrl"]

deploy_transport(package_url, package_name, package_description='', replacements=None, extractions=None)

Main method to deploy a transport. This uses subfunctions to upload, unpackage and deploy the transport, and creates the required workbench.

Parameters:

Name Type Description Default
package_url str

URL to download the transport package.

required
package_name str

Name of the transport package ZIP file

required
package_description str

Description of the transport package

''
replacements list of dicts

List of replacement values to be applied to all XML files in transport; each dict needs to have two values: - placeholder: text to replace - value: text to replace with

None
extractions list of dicts

List of XML Subtrees to extract each XML file in transport; each dict needs to have two values: - xpath: defining the subtree to extract - enabled: True if the extraction is active

None

Returns: dict: Deploy response or None if the deployment fails.

Source code in pyxecm/otcs.py
def deploy_transport(
    self,
    package_url: str,
    package_name: str,
    package_description: str = "",
    replacements: list | None = None,
    extractions: list | None = None,
) -> dict | None:
    """Main method to deploy a transport. This uses subfunctions to upload,
       unpackage and deploy the transport, and creates the required workbench.

    Args:
        package_url (str): URL to download the transport package.
        package_name (str): Name of the transport package ZIP file
        package_description (str): Description of the transport package
        replacements (list of dicts): List of replacement values to be applied
                                      to all XML files in transport;
                                      each dict needs to have two values:
                                      - placeholder: text to replace
                                      - value: text to replace with
        extractions (list of dicts): List of XML Subtrees to extract
                                     each XML file in transport;
                                     each dict needs to have two values:
                                      - xpath: defining the subtree to extract
                                      - enabled: True if the extraction is active
    Returns:
        dict: Deploy response or None if the deployment fails.
    """

    if replacements is None:
        replacements = []
    if extractions is None:
        extractions = []

    # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
    response = self.get_volume(525)
    transport_root_volume_id = self.get_result_value(response, "id")
    if not transport_root_volume_id:
        logger.error("Failed to retrieve transport root volume")
        return None
    logger.info("Transport root volume ID -> %s", str(transport_root_volume_id))

    response = self.get_node_by_parent_and_name(
        transport_root_volume_id, "Transport Packages"
    )
    transport_package_volume_id = self.get_result_value(response, "id")
    if not transport_package_volume_id:
        logger.error("Failed to retrieve transport package volume")
        return None
    logger.info(
        "Transport package volume ID -> %s", str(transport_package_volume_id)
    )

    # Step 1: Upload Transport Package
    logger.info("Check if transport package -> %s already exists...", package_name)
    response = self.get_node_by_parent_and_name(
        transport_package_volume_id, package_name
    )
    package_id = self.get_result_value(response, "id")
    if package_id:
        logger.info(
            "Transport package -> %s does already exist; existing package ID -> %s",
            package_name,
            str(package_id),
        )
    else:
        logger.info(
            "Transport package -> %s does not yet exist, loading from -> %s",
            package_name,
            package_url,
        )
        # If we have string replacements configured execute them now:
        if replacements:
            logger.info(
                "Transport -> %s has replacements -> %s",
                package_name,
                str(replacements),
            )
            self.replace_transport_placeholders(package_url, replacements)
        else:
            logger.info("Transport -> %s has no replacements!", package_name)
        # If we have data extractions configured execute them now:
        if extractions:
            logger.info(
                "Transport -> %s has extractions -> %s",
                package_name,
                str(extractions),
            )
            self.extract_transport_data(package_url, extractions)
        else:
            logger.info("Transport -> %s has no extractions!", package_name)
        # Upload package to Extended ECM:
        response = self.upload_file_to_volume(
            package_url, package_name, "application/zip", 531
        )
        package_id = self.get_result_value(response, "id")
        if not package_id:
            logger.error("Failed to upload transport package -> %s", package_url)
            return None
        logger.info(
            "Successfully uploaded transport package -> %s; new package ID -> %s",
            package_name,
            str(package_id),
        )

    # Step 2: Create Transport Workbench (if not yet exist)
    workbench_name = package_name.split(".")[0]
    logger.info("Check if workbench -> %s is already deployed...", workbench_name)
    # check if the package name has the suffix "(deployed)" - this indicates it is alreadey
    # successfully deployed (see renaming at the end of this method)
    response = self.get_node_by_parent_and_name(
        transport_root_volume_id, workbench_name + " (deployed)"
    )
    workbench_id = self.get_result_value(response, "id")
    if workbench_id:
        logger.info(
            "Workbench -> %s has already been deployed successfully; existing workbench ID -> %s; skipping transport",
            workbench_name,
            str(workbench_id),
        )
        # we return and skip this transport...
        return response
    else:
        logger.info("Check if workbench -> %s already exists...", workbench_name)
        response = self.get_node_by_parent_and_name(
            transport_root_volume_id, workbench_name
        )
        workbench_id = self.get_result_value(response, "id")
        if workbench_id:
            logger.info(
                "Workbench -> %s does already exist but is not successfully deployed; existing workbench ID -> %s",
                workbench_name,
                str(workbench_id),
            )
        else:
            response = self.create_transport_workbench(workbench_name)
            workbench_id = self.get_result_value(response, "id")
            if not workbench_id:
                logger.error("Failed to create workbench -> %s", workbench_name)
                return None
            logger.info(
                "Successfully created workbench -> %s; new workbench ID -> %s",
                workbench_name,
                str(workbench_id),
            )

    # Step 3: Unpack Transport Package to Workbench
    logger.info(
        "Unpack transport package -> %s (%s) to workbench -> %s (%s)",
        package_name,
        str(package_id),
        workbench_name,
        str(workbench_id),
    )
    response = self.unpack_transport_package(package_id, workbench_id)
    if not response:
        logger.error("Failed to unpack the transport package -> %s", package_name)
        return None
    logger.info(
        "Successfully unpackaged to workbench -> %s (%s)",
        workbench_name,
        str(workbench_id),
    )

    # Step 4: Deploy Workbench
    logger.info("Deploy workbench -> %s (%s)", workbench_name, str(workbench_id))
    response = self.deploy_workbench(workbench_id)
    if not response:
        logger.error("Failed to deploy workbench -> %s", workbench_name)
        return None

    logger.info(
        "Successfully deployed workbench -> %s (%s)",
        workbench_name,
        str(workbench_id),
    )
    self.rename_node(
        workbench_id,
        workbench_name + " (deployed)",
        package_description,
    )

    return response

deploy_workbench(workbench_id)

Deploy an existing Workbench.

Parameters:

Name Type Description Default
workbench_d int

ID of the workbench to be deployed

required

Returns: dict: Deploy response or None if the deployment fails.

Source code in pyxecm/otcs.py
def deploy_workbench(self, workbench_id: int) -> dict | None:
    """Deploy an existing Workbench.

    Args:
        workbench_d (int): ID of the workbench to be deployed
    Returns:
        dict: Deploy response or None if the deployment fails.
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(workbench_id) + "/deploy"
    request_header = self.request_form_header()

    logger.info(
        "Deploy workbench with ID -> %s; calling -> %s",
        str(workbench_id),
        request_url,
    )

    retries = 0
    while True:
        # As this is a potentially long-running request we put it in try / except:
        try:
            response = requests.post(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=None,
            )
        except requests.exceptions.RequestException as exception:
            logger.error(
                "Error deploying workbench -> %s; error -> %s",
                str(workbench_id),
                exception.strerror,
            )
            return None
        if response.ok:
            response_dict = self.parse_request_response(response)
            if not response_dict:
                logger.error("Error deploying workbench -> %s", str(workbench_id))
                return None
            return response_dict
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.warning(
                "Failed to depoloy workbench -> %s; status -> %s; error -> %s",
                workbench_id,
                response.status_code,
                response.text,
            )
            return None

download_config_file(otcs_url_suffix, file_path, search='', replace='')

Download a config file from a given OTCS URL. This is NOT for downloading documents from within the OTCS repository but for configuration files such as app packages for MS Teams.

Parameters:

Name Type Description Default
otcs_url_suffix str

OTCS URL suffix starting typically starting with /cs/cs?func=, e.g. /cs/cs?func=officegroups.DownloadTeamsPackage

required
file_path str

local path to save the file (direcotry + filename)

required
search str

optional string to search for a replacement

''
replace str

optional replacement

''

Returns: bool: True if the download succeeds, False otherwise

Source code in pyxecm/otcs.py
def download_config_file(
    self, otcs_url_suffix: str, file_path: str, search: str = "", replace: str = ""
) -> bool:
    """Download a config file from a given OTCS URL. This is NOT
        for downloading documents from within the OTCS repository
        but for configuration files such as app packages for MS Teams.

    Args:
        otcs_url_suffix (str): OTCS URL suffix starting typically starting
                                  with /cs/cs?func=,
                                  e.g. /cs/cs?func=officegroups.DownloadTeamsPackage
        file_path (str): local path to save the file (direcotry + filename)
        search (str, optional): optional string to search for a replacement
        replace (str, optional): optional replacement
    Returns:
        bool: True if the download succeeds, False otherwise
    """

    request_url = self.config()["baseUrl"] + otcs_url_suffix
    # request_header = self.cookie()
    request_header = self.request_download_header()

    logger.info("Download config file from URL -> %s", request_url)

    try:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=REQUEST_TIMEOUT,
        )
        response.raise_for_status()
    except requests.exceptions.HTTPError as errh:
        logger.error("Http Error -> %s", errh.strerror)
        return False
    except requests.exceptions.ConnectionError as errc:
        logger.error("Error Connecting -> %s", errc.strerror)
        return False
    except requests.exceptions.Timeout as errt:
        logger.error("Timeout Error -> %s", errt.strerror)
        return False
    except requests.exceptions.RequestException as err:
        logger.error("Request error -> %s", err.strerror)
        return False

    content = response.content

    if search:
        logger.info(
            "Search for all occurances of %s in the config file and replace them with %s",
            search,
            replace,
        )
        content = content.replace(search.encode("utf-8"), replace.encode("utf-8"))

    # Open file in write binary mode
    with open(file=file_path, mode="wb") as file:
        # Write the content to the file
        file.write(content)

    logger.info(
        "Successfully downloaded config file -> %s to -> %s; status code -> %s",
        request_url,
        file_path,
        response.status_code,
    )

    return True

download_document(node_id, file_path, version_number='')

Download a document from Extended ECM to local file system.

Parameters:

Name Type Description Default
node_id int

node ID of the document to download

required
file_path str

local file path (directory)

required
version_number str

version of the document to download. If version = "" then download the latest version.

''

Returns: bool: True if the document has been download to the specified file. False otherwise.

Source code in pyxecm/otcs.py
def download_document(
    self, node_id: int, file_path: str, version_number: str = ""
) -> bool:
    """Download a document from Extended ECM to local file system.

    Args:
        node_id (int): node ID of the document to download
        file_path (str): local file path (directory)
        version_number (str): version of the document to download.
                                 If version = "" then download the latest
                                 version.
    Returns:
        bool: True if the document has been download to the specified file.
                 False otherwise.
    """

    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        logger.error("Directory -> %s does not exist", directory)
        return False

    if not version_number:
        response = self.get_latest_document_version(node_id)
        if not response:
            logger.error(
                "Cannot get latest version of document with ID -> %s", str(node_id)
            )
        version_number = response["data"]["version_number"]

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/versions/"
        + str(version_number)
        + "/content"
    )
    request_header = self.request_download_header()

    logger.info(
        "Download document with node ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            content = response.content
            break
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to download document with node ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return False

    logger.info("Writing document content to file -> %s", file_path)

    # Open file in write binary mode
    with open(file=file_path, mode="wb") as file:
        # Write the content to the file
        file.write(content)

    return True

exist_result_item(response, key, value, property_name='properties')

Check existence of key / value pair in the response properties of an Extended ECM REST API call.

Parameters:

Name Type Description Default
response dict

REST response from an OTCS REST Call

required
key str

property name (key)

required
value str

value to find in the item with the matching key

required
property_name str

name of the substructure that includes the values

'properties'

Returns: bool: True if the value was found, False otherwise

Source code in pyxecm/otcs.py
def exist_result_item(
    self, response: dict, key: str, value: str, property_name: str = "properties"
) -> bool:
    """Check existence of key / value pair in the response properties of an Extended ECM REST API call.

    Args:
        response (dict): REST response from an OTCS REST Call
        key (str): property name (key)
        value (str): value to find in the item with the matching key
        property_name (str, optional): name of the substructure that includes the values
    Returns:
        bool: True if the value was found, False otherwise
    """

    if not response:
        return False
    if not "results" in response:
        return False

    results = response["results"]
    # check if results is a list or a dict (both is possible - dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value:
        if not "data" in results:
            return False
        data = results["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            if property_name and not property_name in data:
                logger.error(
                    "There's no -> %s dictionary in data -> %s", property_name, data
                )
                return False
            properties = data[property_name]
            if isinstance(properties, dict):
                if key in properties:
                    return properties[key] == value
                else:
                    return False
            elif isinstance(properties, list):
                # properties is a list we iterate through the list and try to find the key:
                for item in properties:
                    if key in item and item[key] == value:
                        return True
            else:
                logger.error(
                    "Properties needs to be a list or dict but it is -> %s",
                    str(type(properties)),
                )
                return False
        elif isinstance(data, list):
            # data is a list
            for item in data:
                if property_name and not property_name in item:
                    logger.error(
                        "There's no -> %s dictionary in the data list item -> %s",
                        property_name,
                        item,
                    )
                    continue
                # if properties if passed as empty string then we assume that
                # the key fields are directly in the item dictionary. This is
                # the case e.g. with the V2 Proxy APIs
                if not property_name:
                    properties = item
                else:
                    properties = item[property_name]
                if key in properties and properties[key] == value:
                    return True
            return False
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return False
    elif isinstance(results, list):
        # result is a list - we need index value
        for result in results:
            if not "data" in result:
                continue
            data = result["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data[property_name]
                if key in properties and properties[key] == value:
                    return True
            elif isinstance(data, list):
                # data is a list we iterate through the list and try to find the key:
                for item in data:
                    properties = item[property_name]
                    if key in properties and properties[key] == value:
                        return True
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s",
                    str(type(data)),
                )
                return False
        return False
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return False

extract_transport_data(zip_file_path, extractions)

Search and extract XML data from the transport package

Parameters:

Name Type Description Default
zip_file_path str

Path to transport zip file

required
extractions list of dicts

List of extraction values; dict needs to have two values: * xpath: structure to find * enabed (optional): if the extraction is active

required

Returns: True if successful, False otherwise. THIS METHOD MODIFIES EXTRACTIONS BY ADDING A NEW KEY "data" TO EACH EXTRACTION ELEMENT!!

Source code in pyxecm/otcs.py
def extract_transport_data(self, zip_file_path: str, extractions: list) -> bool:
    """Search and extract XML data from the transport package

    Args:
        zip_file_path (str): Path to transport zip file
        extractions (list of dicts): List of extraction values; dict needs to have two values:
                                     * xpath: structure to find
                                     * enabed (optional): if the extraction is active
    Returns:
        True if successful, False otherwise. THIS METHOD MODIFIES EXTRACTIONS
        BY ADDING A NEW KEY "data" TO EACH EXTRACTION ELEMENT!!
    """

    if not os.path.isfile(zip_file_path):
        logger.error("Zip file -> %s not found.", zip_file_path)
        return False

    # Extract the zip file to a temporary directory
    zip_file_folder = os.path.splitext(zip_file_path)[0]
    with zipfile.ZipFile(zip_file_path, "r") as zfile:
        zfile.extractall(zip_file_folder)

    # Extract data from all XML files in the directory and its subdirectories
    for extraction in extractions:
        if not "xpath" in extraction:
            logger.error(
                "Extraction needs an XPath but it is not specified. Skipping..."
            )
            continue
        if "enabled" in extraction and not extraction["enabled"]:
            logger.info(
                "Extraction for transport -> %s is disabled. Skipping...",
                zip_file_path,
            )
            continue

        xpath = extraction["xpath"]
        logger.info(
            "Using xpath -> %s to extract the data",
            xpath,
        )

        # This delivers a list of strings containing the extracted data:
        extracted_data = XML.extract_from_xml_files(
            zip_file_folder,
            xpath,
        )
        if extracted_data:
            logger.info(
                "Extraction with XPath -> %s has been successfully completed for Transport package -> %s",
                xpath,
                zip_file_folder,
            )
            # Add the extracted elements to the extraction data structure (dict).
            extraction["data"] = extracted_data
        else:
            logger.warning(
                "Extraction with XPath -> %s has not delivered any data for Transport package -> %s",
                xpath,
                zip_file_folder,
            )
            extraction["data"] = []

    # Return the path to the new zip file
    return True

get_business_object_type(external_system_id, type_name, expand_workspace_type=True, expand_external_system=True)

Get business object type information. Unfortunately this REST API is pretty much limited. It does not return Field names of external system properties and also does not return property groups defined.

Parameters:

Name Type Description Default
external_system_id str

External system Id (such as "TM6")

required
type_name str

Type name of the business object (such as "SAP Customer")

required

Returns: dict: Business Object Type information or None if the request fails.

Example response:
{
    'businessProperties': [
        {
            'attributeID': '14012_29',
            'categoryID': '14012',
            'name': 'Name',
            'type': 'String'
        },
        {
            'attributeID': '14012_28',
            'categoryID': '14012',
            'name': 'Customer Number',
            'type': 'String'
        }
    ]
    'bwsinfo': {'id': None},
    'cadxref_doc_info': {'has_relation': False},
    'categories': [],
    'claimed_doc_info': {'is_claimed': False},
    'columns': [{...}, {...}, {...}, {...}],
    'doctemplates_info': {'isInDocTemplateVolTree': False},
    'followups': [],
    'nicknames': {'nickname': '16568'},
    'properties': {
        'advanced_versioning': None,
        'container': False,
        'container_size': 0,
        'create_date': '2017-11-23T16:43:34Z',
        'create_user_id': 1000,
        'description': '',
        'description_multilingual': {...},
        'external_create_date': None,
        'external_identity': '',
        ...
    },
    'rmiconsdata': {'class_id': 0, 'official': 0, 'show_classify': False, 'show_hold': False, 'show_hold_tab': False, 'show_label_tab': True, 'show_official': False, 'show_xref': False, 'show_xref_tab': False},
    'sestatus_doc_info': {'is_se_document': False, 'sync_tooltip': ''},
    'sharing_info': {'is_shared': False, 'sync_state': -1},
    'showmainruleicon': False,
    ...
}
Source code in pyxecm/otcs.py
def get_business_object_type(
    self,
    external_system_id: str,
    type_name: str,
    expand_workspace_type: bool = True,
    expand_external_system: bool = True,
) -> dict | None:
    """Get business object type information. Unfortunately this REST API is
       pretty much limited. It does not return Field names of external system properties
       and also does not return property groups defined.

    Args:
        external_system_id (str): External system Id (such as "TM6")
        type_name (str): Type name of the business object (such as "SAP Customer")
    Returns:
        dict: Business Object Type information or None if the request fails.

        Example response:
        {
            'businessProperties': [
                {
                    'attributeID': '14012_29',
                    'categoryID': '14012',
                    'name': 'Name',
                    'type': 'String'
                },
                {
                    'attributeID': '14012_28',
                    'categoryID': '14012',
                    'name': 'Customer Number',
                    'type': 'String'
                }
            ]
            'bwsinfo': {'id': None},
            'cadxref_doc_info': {'has_relation': False},
            'categories': [],
            'claimed_doc_info': {'is_claimed': False},
            'columns': [{...}, {...}, {...}, {...}],
            'doctemplates_info': {'isInDocTemplateVolTree': False},
            'followups': [],
            'nicknames': {'nickname': '16568'},
            'properties': {
                'advanced_versioning': None,
                'container': False,
                'container_size': 0,
                'create_date': '2017-11-23T16:43:34Z',
                'create_user_id': 1000,
                'description': '',
                'description_multilingual': {...},
                'external_create_date': None,
                'external_identity': '',
                ...
            },
            'rmiconsdata': {'class_id': 0, 'official': 0, 'show_classify': False, 'show_hold': False, 'show_hold_tab': False, 'show_label_tab': True, 'show_official': False, 'show_xref': False, 'show_xref_tab': False},
            'sestatus_doc_info': {'is_se_document': False, 'sync_tooltip': ''},
            'sharing_info': {'is_shared': False, 'sync_state': -1},
            'showmainruleicon': False,
            ...
        }
    """

    query = {
        "expand_ext_system": expand_external_system,
        "expand_wksp_type": expand_workspace_type,
    }

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    encoded_type_name = type_name.replace("/", "%2F")

    request_url = (
        self.config()["externalSystemUrl"]
        + "/"
        + external_system_id
        + "/botypes/"
        + encoded_type_name
        + "?{}".format(encoded_query)
    )
    request_header = self.request_form_header()

    logger.info(
        "Get business object type -> %s for external system -> %s; calling -> %s",
        type_name,
        external_system_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get business object type -> %s; status -> %s; error -> %s",
                type_name,
                response.status_code,
                response.text,
            )
            return None

get_business_object_types()

Get information for all configured business object types.

Returns: dict: Workspace Types information (for all external systems) or None if the request fails.

Source code in pyxecm/otcs.py
def get_business_object_types(self) -> dict | None:
    """Get information for all configured business object types.

    Args:
        None
    Returns:
        dict: Workspace Types information (for all external systems)
              or None if the request fails.
    """

    request_url = self.config()["businessObjectTypesUrl"]
    request_header = self.request_form_header()

    logger.info(
        "Get all business object types; calling -> %s",
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get business object types; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_business_objects(external_system_id, type_name, where_clauses=None, limit=None, page=None)

Get all business objects for an external system and a given business object type.

Parameters:

Name Type Description Default
external_system_id str

External system Id (such as "TM6")

required
type_name str

Type name of the business object (such as "SAP Customer")

required
where_clause dict

filter the results based on 1 or kultiple where clauses (THE NAME CONVENTION FOR THE FIELDS IS UNCLEAR)

required
limit int

maximum result items

None
page int

page for chunked result lists

None

Returns: dict: Business Object information (for all results) or None if the request fails.

Example response (for a Salesforce Account):
{
    'links': {'data': {...}},
    'paging': {'limit': 500, 'page': 1, 'page_total': 1, 'range_max': 15, 'range_min': 1, 'total_count': 15},
    'results': {
        'column_descriptions': [
            {
                'fieldLabel': 'AccountDetail.AccountID',
                'fieldName': 'Account.ID',
                'keyField': 'X',
                'length': 18,
                'position': 4
            },
            {
                'fieldLabel': 'AccountName',
                'fieldName': 'Account.Name',
                'keyField': ' ',
                'length': 255,
                'position': 2
            },
            {
                'fieldLabel': 'AccountNumber',
                'fieldName': 'Account.AccountNumber',
                'keyField': ' ',
                'length': 40,
                'position': 3
            },
            ...
        ]
        'max_rows_exceeded': False,
        'result_rows': [
            {
                'AccountDetail.AccountID': '001Dn00000w0bCQIAY',
                'AccountDetail.AccountName': 'Jet Stream Inc.',
                'AccountDetail.AccountNumber': '1234567',
                'AccountDetail.AccountOwner': 'Nick Wheeler',
                'AccountDetail.AnnualRevenue': '$900001',
                'AccountDetail.Description': '',
                'AccountDetail.Employees': '',
                'AccountDetail.Industry': 'Biotechnology',
                'AccountDetail.ParentAccount': '',
                ...
            },
            ...
        ]
    }
}
Source code in pyxecm/otcs.py
def get_business_objects(
    self,
    external_system_id: str,
    type_name: str,
    where_clauses: dict | None = None,
    limit: int | None = None,
    page: int | None = None,
) -> dict | None:
    """Get all business objects for an external system and a given business object type.

    Args:
        external_system_id (str): External system Id (such as "TM6")
        type_name (str): Type name of the business object (such as "SAP Customer")
        where_clause (dict, optional): filter the results based on 1 or kultiple
                                       where clauses (THE  NAME CONVENTION FOR THE
                                       FIELDS IS UNCLEAR)
        limit (int, optional): maximum result items
        page (int, optional): page for chunked result lists
    Returns:
        dict: Business Object information (for all results)
              or None if the request fails.

        Example response (for a Salesforce Account):
        {
            'links': {'data': {...}},
            'paging': {'limit': 500, 'page': 1, 'page_total': 1, 'range_max': 15, 'range_min': 1, 'total_count': 15},
            'results': {
                'column_descriptions': [
                    {
                        'fieldLabel': 'AccountDetail.AccountID',
                        'fieldName': 'Account.ID',
                        'keyField': 'X',
                        'length': 18,
                        'position': 4
                    },
                    {
                        'fieldLabel': 'AccountName',
                        'fieldName': 'Account.Name',
                        'keyField': ' ',
                        'length': 255,
                        'position': 2
                    },
                    {
                        'fieldLabel': 'AccountNumber',
                        'fieldName': 'Account.AccountNumber',
                        'keyField': ' ',
                        'length': 40,
                        'position': 3
                    },
                    ...
                ]
                'max_rows_exceeded': False,
                'result_rows': [
                    {
                        'AccountDetail.AccountID': '001Dn00000w0bCQIAY',
                        'AccountDetail.AccountName': 'Jet Stream Inc.',
                        'AccountDetail.AccountNumber': '1234567',
                        'AccountDetail.AccountOwner': 'Nick Wheeler',
                        'AccountDetail.AnnualRevenue': '$900001',
                        'AccountDetail.Description': '',
                        'AccountDetail.Employees': '',
                        'AccountDetail.Industry': 'Biotechnology',
                        'AccountDetail.ParentAccount': '',
                        ...
                    },
                    ...
                ]
            }
        }
    """

    query = {
        "ext_system_id": external_system_id,
        "bo_type": type_name,
    }
    if limit:
        query["limit"] = limit
    if page:
        query["page"] = page
    if where_clauses:
        query.update(
            {("where_" + key): value for key, value in where_clauses.items()}
        )

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["businessObjectsUrl"] + "?{}".format(encoded_query)
    request_header = self.request_form_header()

    logger.info(
        "Get all business objects of type -> %s from external system -> %s; calling -> %s",
        type_name,
        external_system_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get business objects of type -> %s from external system -> %s; status -> %s; error -> %s",
                type_name,
                external_system_id,
                response.status_code,
                response.text,
            )
            return None

Get business object type information. Unfortunately this REST API is pretty much limited. It does not return Field names of external system properties and also does not return property groups defined.

Parameters:

Name Type Description Default
external_system_id str

External system Id (such as "TM6")

required
type_name str

Type name of the business object (such as "SAP Customer")

required

Returns: dict: Business Object Search Form or None if the request fails.

Source code in pyxecm/otcs.py
def get_business_objects_search(
    self,
    external_system_id: str,
    type_name: str,
) -> dict | None:
    """Get business object type information. Unfortunately this REST API is
       pretty much limited. It does not return Field names of external system properties
       and also does not return property groups defined.

    Args:
        external_system_id (str): External system Id (such as "TM6")
        type_name (str): Type name of the business object (such as "SAP Customer")
    Returns:
        dict: Business Object Search Form or None if the request fails.
    """

    query = {
        "ext_system_id": external_system_id,
        "bo_type": type_name,
    }

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["businessObjectsSearchUrl"] + "?{}".format(
        encoded_query
    )
    request_header = self.request_form_header()

    logger.info(
        "Get search form for business object type -> %s and external system -> %s; calling -> %s",
        type_name,
        external_system_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get search form for business object type -> %s and external system -> %s; status -> %s; error -> %s",
                type_name,
                external_system_id,
                response.status_code,
                response.text,
            )
            return None

get_document_content(node_id, version_number='')

Get document content from Extended ECM.

Parameters:

Name Type Description Default
node_id int

node ID of the document to download

required
version_number str

version of the document to download. If version = "" then download the latest version.

''

Returns: bytes: content of the file or None in case of an error.

Source code in pyxecm/otcs.py
def get_document_content(self, node_id: int, version_number: str = "") -> bytes:
    """Get document content from Extended ECM.

    Args:
        node_id (int): node ID of the document to download
        version_number (str, optional): version of the document to download.
                                        If version = "" then download the latest
                                        version.
    Returns:
        bytes: content of the file or None in case of an error.
    """

    if not version_number:
        response = self.get_latest_document_version(node_id)
        if not response:
            logger.error(
                "Cannot get latest version of document with ID -> %s", str(node_id)
            )
        version_number = response["data"]["version_number"]

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/versions/"
        + str(version_number)
        + "/content"
    )
    request_header = self.request_download_header()

    logger.info(
        "Retrieve document with node ID -> %s and version -> %s; calling -> %s",
        str(node_id),
        str(version_number),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            content = response.content
            break
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to download document with node ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

    return content

get_document_templates(parent_id)

Get all document templates for a given target location.

Parameters:

Name Type Description Default
parent_id int

node ID of target location (e.g. a folder)

required

Returns:

Name Type Description
dict

response of the REST call (converted to a Python dictionary)

Example response:

'results': [ { 'container': False, 'hasTemplates': False, 'name': 'Document', 'subtype': 144, 'templates': [ { 'description_multilingual': {...}, 'id': 16817, 'isDPWizardAvailable': False, 'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'name': 'Innovate Procurement Contract Template 2022.docx', 'name_multilingual': {...}, 'size': 144365, 'sizeformatted': '141 KB', 'type': 144 }, { ... } ] }

]

Source code in pyxecm/otcs.py
def get_document_templates(self, parent_id: int):
    """Get all document templates for a given target location.

    Args:
        parent_id (int): node ID of target location (e.g. a folder)

    Returns:
        dict: response of the REST call (converted to a Python dictionary)

        Example response:
        'results': [
            {
                'container': False,
                'hasTemplates': False,
                'name': 'Document',
                'subtype': 144,
                'templates': [
                    {
                        'description_multilingual': {...},
                        'id': 16817,
                        'isDPWizardAvailable': False,
                        'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                        'name': 'Innovate Procurement Contract Template 2022.docx',
                        'name_multilingual': {...},
                        'size': 144365,
                        'sizeformatted': '141 KB',
                        'type': 144
                    },
                    {
                        ...
                    }
                ]
            }
        ]
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(parent_id)
        + "/doctemplates?subtypes={144}&sidepanel_subtypes={144}"
    )
    request_header = self.request_form_header()

    logger.info(
        "Get document templates for target location -> %s (parent ID); calling -> %s",
        str(parent_id),
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get document templates for parent folder -> %s; status -> %s; error -> %s",
                str(parent_id),
                response.status_code,
                response.text,
            )
            return None

get_external_system_connection(connection_name, show_error=False)

Get Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

Parameters:

Name Type Description Default
connection_name str

Name of the connection

required
show_error bool

If True, treat as error if connection is not found.

False

Returns: dict: External system Details or None if the REST call fails.

Source code in pyxecm/otcs.py
def get_external_system_connection(
    self, connection_name: str, show_error: bool = False
) -> dict | None:
    """Get Extended ECM external system connection (e.g. SAP, Salesforce, SuccessFactors).

    Args:
        connection_name (str): Name of the connection
        show_error (bool, optional): If True, treat as error if connection is not found.
    Returns:
        dict: External system Details or None if the REST call fails.
    """

    request_url = (
        self.config()["externalSystemUrl"] + "/" + connection_name + "/config"
    )
    request_header = self.cookie()

    logger.info(
        "Get external system connection -> %s; calling -> %s",
        connection_name,
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to get external system connection -> %s; status -> %s; error -> %s",
                    connection_name,
                    response.status_code,
                    response.text,
                )
            else:
                logger.info("External system -> %s not found.", connection_name)
            return None

get_group(name, show_error=False)

Lookup Content Server group.

Parameters:

Name Type Description Default
name str

name of the group

required
show_error bool

if True, treat as error if group is not found

False

Returns: dict: Group information or None if the group is not found. The returned information has a structure like this: "data": [ { "id": 0, "name": "string", ... } ] To access the id of the first group found use ["data"][0]["id"]

Source code in pyxecm/otcs.py
def get_group(self, name: str, show_error: bool = False) -> dict | None:
    """Lookup Content Server group.

    Args:
        name (str): name of the group
        show_error (bool): if True, treat as error if group is not found
    Returns:
        dict: Group information or None if the group is not found.
        The returned information has a structure like this:
        "data": [
            {
                "id": 0,
                "name": "string",
                ...
            }
        ]
        To access the id of the first group found use ["data"][0]["id"]
    """

    # Add query parameters (these are NOT passed via JSon body!)
    # type = 1 ==> Group
    request_url = self.config()["membersUrlv2"] + "?where_type=1&query={}".format(
        name
    )
    request_header = self.request_form_header()

    logger.info("Get group with name -> %s; calling -> %s", name, request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to get group -> %s; status -> %s; error -> %s",
                    name,
                    response.status_code,
                    response.text,
                )
            else:
                logger.info("Group -> %s not found.", name)
            return None

get_group_members(group, member_type, limit=100)

Get Content Server group members.

Parameters:

Name Type Description Default
group int

ID of the group.

required
member_type int

users = 0, groups = 1

required
limit int

max number of results (internal default is 25)

100

Returns: dict: Group members or None if the group members couldn't be found.

Source code in pyxecm/otcs.py
def get_group_members(
    self, group: int, member_type: int, limit: int = 100
) -> dict | None:
    """Get Content Server group members.

    Args:
        group (int): ID of the group.
        member_type (int): users = 0, groups = 1
        limit (int, optional): max number of results (internal default is 25)
    Returns:
        dict: Group members or None if the group members couldn't be found.
    """

    # default limit is 25 which may not be enough for groups with many members
    # where_type = 1 makes sure we just get groups and not users
    request_url = (
        self.config()["membersUrlv2"]
        + "/"
        + str(group)
        + "/members?where_type="
        + str(member_type)
        + "&limit="
        + str(limit)
    )
    request_header = self.request_form_header()

    logger.info(
        "Getting members of group with ID -> %s; calling -> %s",
        str(group),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get members of group -> %s; status -> %s; error -> %s",
                str(group),
                response.status_code,
                response.text,
            )
            return None

get_latest_document_version(node_id)

Get latest version of a document node based on the node ID.

Returns: dict: Node information or None if no node with this ID is found.

Source code in pyxecm/otcs.py
def get_latest_document_version(self, node_id: int) -> dict | None:
    """Get latest version of a document node based on the node ID.

    Args:
        node_id (int) is the node Id of the node
    Returns:
        dict: Node information or None if no node with this ID is found.
    """

    request_url = (
        self.config()["nodesUrl"] + "/" + str(node_id) + "/versions/latest"
    )
    request_header = self.request_form_header()

    logger.info(
        "Get latest version of document with node ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get latest version of document with node ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

get_node(node_id, timeout=REQUEST_TIMEOUT)

Get a node based on the node ID.

Parameters:

Name Type Description Default
timeout int

timeout for the request in seconds

REQUEST_TIMEOUT

Returns: dict: Node information or None if no node with this ID is found. "results": [ { "data": [ { "columns": [ { "data_type": 0, "key": "string", "name": "string", "sort_key": "string" } ], "properties": [ { "advanced_versioning": true, "container": true, "container_size": 0, "create_date": "string", "create_user_id": 0, "description": "string", "description_multilingual": { "en": "string", "de": "string" }, "external_create_date": "2019-08-24", "external_identity": "string", "external_identity_type": "string", "external_modify_date": "2019-08-24", "external_source": "string", "favorite": true, "guid": "string", "hidden": true, "icon": "string", "icon_large": "string", "id": 0, "modify_date": "2019-08-24", "modify_user_id": 0, "name": "string", "name_multilingual": { "en": "string", "de": "string" }, "owner": "string", "owner_group_id": 0, "owner_user_id": 0, "parent_id": 0, "reserved": true, "reserved_date": "string", "reserved_user_id": 0, "status": 0, "type": 0, "type_name": "string", "versionable": true, "versions_control_advanced": true, "volume_id": 0 } ] } ] } ]

Source code in pyxecm/otcs.py
def get_node(self, node_id: int, timeout: int = REQUEST_TIMEOUT) -> dict | None:
    """Get a node based on the node ID.

    Args:
        node_id (int) is the node Id of the node
        timeout (int, optional): timeout for the request in seconds
    Returns:
        dict: Node information or None if no node with this ID is found.
        "results": [
            {
                "data": [
                    {
                        "columns": [
                            {
                            "data_type": 0,
                            "key": "string",
                            "name": "string",
                            "sort_key": "string"
                            }
                        ],
                        "properties": [
                            {
                                "advanced_versioning": true,
                                "container": true,
                                "container_size": 0,
                                "create_date": "string",
                                "create_user_id": 0,
                                "description": "string",
                                "description_multilingual": {
                                    "en": "string",
                                    "de": "string"
                                },
                                "external_create_date": "2019-08-24",
                                "external_identity": "string",
                                "external_identity_type": "string",
                                "external_modify_date": "2019-08-24",
                                "external_source": "string",
                                "favorite": true,
                                "guid": "string",
                                "hidden": true,
                                "icon": "string",
                                "icon_large": "string",
                                "id": 0,
                                "modify_date": "2019-08-24",
                                "modify_user_id": 0,
                                "name": "string",
                                "name_multilingual": {
                                    "en": "string",
                                    "de": "string"
                                },
                                "owner": "string",
                                "owner_group_id": 0,
                                "owner_user_id": 0,
                                "parent_id": 0,
                                "reserved": true,
                                "reserved_date": "string",
                                "reserved_user_id": 0,
                                "status": 0,
                                "type": 0,
                                "type_name": "string",
                                "versionable": true,
                                "versions_control_advanced": true,
                                "volume_id": 0
                            }
                        ]
                    }
                ]
            }
        ]
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.info("Get node with ID -> %s; calling -> %s", str(node_id), request_url)

    retries = 0
    while True:
        try:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=timeout,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get node with ID -> %s; status -> %s; error -> %s",
                    str(node_id),
                    response.status_code,
                    response.text,
                )
                return None
        except requests.exceptions.Timeout:
            if retries <= REQUEST_MAX_RETRIES:
                logger.warning(
                    "Request timed out. Retrying in %s seconds...",
                    str(REQUEST_RETRY_DELAY),
                )
                retries += 1
                time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
            else:
                logger.error(
                    "Failed to get node with ID -> %s; timeout error", str(node_id)
                )
                # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                logger.warning("Turn timeouts off and wait forever...")
                timeout = None

get_node_actions(node_id, filter_actions=None)

Get allowed actions for a node.

Parameters:

Name Type Description Default
node_id int

description

required
filter_actions list

description

None

Returns:

Name Type Description
dict dict

description

Source code in pyxecm/otcs.py
def get_node_actions(self, node_id: int, filter_actions: list = None) -> dict:
    """Get allowed actions for a node.

    Args:
        node_id (int): _description_
        filter_actions (list, optional): _description_

    Returns:
        dict: _description_
    """

    actions_post_body = {"ids": [node_id], "actions": filter_actions}

    request_url = self.config()["nodesUrlv2"] + "/actions"

    request_header = self.request_form_header()

    logger.info(
        "Get actions for node with ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=actions_post_body,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get actions for node with ID -> %s; status -> %s; error -> %s",
                node_id,
                response.status_code,
                response.text,
            )
            return None

get_node_by_parent_and_name(parent_id, name, fields='properties', show_error=False)

Get a node based on the parent ID and name. This method does basically a query with "where_name" and the "result" is a list.

Parameters:

Name Type Description Default
fields str

which fields to retrieve. This can have a big impact on performance!

'properties'
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this name is found in parent. Access to node ID with: response["results"][0]["data"]["properties"]["id"]

Source code in pyxecm/otcs.py
def get_node_by_parent_and_name(
    self,
    parent_id: int,
    name: str,
    fields: str = "properties",
    show_error: bool = False,
) -> dict | None:
    """Get a node based on the parent ID and name. This method does basically
       a query with "where_name" and the "result" is a list.

    Args:
        parent_id (int) is the node Id of the parent node
        name (str) is the name of the node to get
        fields (str, optional): which fields to retrieve. This can have a big impact on performance!
        show_error (bool, optional): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this name is found in parent.
                    Access to node ID with: response["results"][0]["data"]["properties"]["id"]
    """

    # Add query parameters (these are NOT passed via JSon body!)
    query = {"where_name": name}
    if fields:
        query["fields"] = fields
    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(parent_id)
        + "/nodes?{}".format(encoded_query)
    )
    request_header = self.request_form_header()

    logger.info(
        "Get node with name -> %s and parent ID -> %s; calling -> %s",
        name,
        str(parent_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to get node with name -> %s and parent ID -> %s; status -> %s; error -> %s",
                    name,
                    str(parent_id),
                    response.status_code,
                    response.text,
                )
            else:
                logger.info(
                    "Node with name -> %s and parent ID -> %s not found.",
                    name,
                    str(parent_id),
                )
            return None

get_node_by_volume_and_path(volume_type, path=None)

Get a node based on the volume and path (list of container items).

Parameters:

Name Type Description Default
volume_type int

Volume type ID (default is 141 = Enterprise Workspace) "Records Management" = 550 "Content Server Document Templates" = 20541 "O365 Office Online Volume" = 1296 "Categories Volume" = 133 "Perspectives" = 908 "Perspective Assets" = 954 "Facets Volume" = 901 "Transport Warehouse" = 525 "Transport Warehouse Workbench" = 528 "Transport Warehouse Package" = 531 "Event Action Center Configuration" = 898 "Classification Volume" = 198 "Support Asset Volume" = 1309 "Physical Objects Workspace" = 413 "Extended ECM" = 882 "Enterprise Workspace" = 141 "Personal Workspace" = 142 "Business Workspaces" = 862

required
path list

list of container items (top down), last item is name of to be retrieved item. If path is empty the node of the volume is returned.

None

Returns: dict: Node information or None if no node with this path is found.

Source code in pyxecm/otcs.py
def get_node_by_volume_and_path(
    self, volume_type: int, path: list | None = None
) -> dict | None:
    """Get a node based on the volume and path (list of container items).

    Args:
        volume_type (int): Volume type ID (default is 141 = Enterprise Workspace)
            "Records Management"                = 550
            "Content Server Document Templates" = 20541
            "O365 Office Online Volume"         = 1296
            "Categories Volume"                 = 133
            "Perspectives"                      = 908
            "Perspective Assets"                = 954
            "Facets Volume"                     = 901
            "Transport Warehouse"               = 525
            "Transport Warehouse Workbench"     = 528
            "Transport Warehouse Package"       = 531
            "Event Action Center Configuration" = 898
            "Classification Volume"             = 198
            "Support Asset Volume"              = 1309
            "Physical Objects Workspace"        = 413
            "Extended ECM"                      = 882
            "Enterprise Workspace"              = 141
            "Personal Workspace"                = 142
            "Business Workspaces"               = 862
        path (list): list of container items (top down), last item is name of to be retrieved item.
                     If path is empty the node of the volume is returned.
    Returns:
        dict: Node information or None if no node with this path is found.
    """

    # If path is not given we use empty list to make the for loop below working in this case as well
    if path is None:
        path = []

    # Preparation: get volume IDs for Transport Warehouse (root volume and Transport Packages)
    response = self.get_volume(volume_type)
    if not response:
        logger.error("Volume type -> %s not found!", str(volume_type))
        return None

    volume_id = self.get_result_value(response, "id")
    logger.info(
        "Volume type -> %s has node ID -> %s", str(volume_type), str(volume_id)
    )

    current_item_id = volume_id

    # in case the path is an empty list
    # we will have the node of the volume:
    node = self.get_node(current_item_id)

    for path_element in path:
        node = self.get_node_by_parent_and_name(current_item_id, path_element)
        path_item_id = self.get_result_value(node, "id")
        if not path_item_id:
            logger.error(
                "Cannot find path element -> %s in container with ID -> %s.",
                path_element,
                str(current_item_id),
            )
            return None
        current_item_id = path_item_id
        logger.debug("Traversing path element with ID -> %s", str(current_item_id))

    return node

get_node_by_workspace_and_path(workspace_id, path, show_error=False)

Get a node based on the workspace ID (= node ID) and path (list of folder names).

Parameters:

Name Type Description Default
workspace_id int

node ID of the workspace

required
path list

list of container items (top down), last item is name of to be retrieved item. If path is empty the node of the volume is returned.

required
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this path is found.

Source code in pyxecm/otcs.py
def get_node_by_workspace_and_path(
    self, workspace_id: int, path: list, show_error: bool = False
) -> dict | None:
    """Get a node based on the workspace ID (= node ID) and path (list of folder names).

    Args:
        workspace_id (int): node ID of the workspace
        path (list): list of container items (top down), last item is name of to be retrieved item.
                     If path is empty the node of the volume is returned.
        show_error (bool, optional): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this path is found.
    """

    current_item_id = workspace_id

    # in case the path is an empty list
    # we will have the node of the workspace:
    node = self.get_node(current_item_id)

    for path_element in path:
        node = self.get_node_by_parent_and_name(current_item_id, path_element)
        current_item_id = self.get_result_value(node, "id")
        if not current_item_id:
            if show_error:
                logger.error("Cannot find path element -> %s!", path_element)
            else:
                logger.info("Cannot find path element -> %s.", path_element)
            return None
        logger.debug(
            "Traversing path element -> %s (%s)", path_element, str(current_item_id)
        )

    return node

get_node_categories(node_id, metadata=True)

Get categories assigned to a node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required
metadata bool

expand the attribute definitions of the category. Default is True.

True

Returns: dict: category response or None if the call to the REST API fails.

Source code in pyxecm/otcs.py
def get_node_categories(self, node_id: int, metadata: bool = True):
    """Get categories assigned to a node.

    Args:
        node_id (int): ID of the node to get the categories for.
        metadata (bool, optional): expand the attribute definitions of the category. Default is True.
    Returns:
        dict: category response or None if the call to the REST API fails.
    """

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/categories"
    if metadata:
        request_url += "?metadata"
    request_header = self.request_form_header()

    logger.info(
        "Get categories of node with ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get categories for node ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

get_node_category(node_id, category_id, metadata=True)

Get a specific category assigned to a node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required
category_id int

ID of the category definition ID (in category volume)

required
metadata bool

expand the attribute definitions of the category. Default is True

True

Returns: dict: category response or None if the call to the REST API fails.

Source code in pyxecm/otcs.py
def get_node_category(self, node_id: int, category_id: int, metadata: bool = True):
    """Get a specific category assigned to a node.

    Args:
        node_id (int): ID of the node to get the categories for.
        category_id (int): ID of the category definition ID (in category volume)
        metadata (bool, optional): expand the attribute definitions of the category. Default is True
    Returns:
        dict: category response or None if the call to the REST API fails.
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/categories/"
        + str(category_id)
    )
    if metadata:
        request_url += "?metadata"
    request_header = self.request_form_header()

    logger.info(
        "Get category with ID -> %s on node with ID -> %s; calling -> %s",
        str(category_id),
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get category with ID -> %s for node ID -> %s; status -> %s; error -> %s",
                str(category_id),
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

get_node_category_definition(node_id, category_name)

Get category definition (category id and attribute IDs and types)

Parameters:

Name Type Description Default
node_id int

node to read the category definition from (e.g. a workspace template or a document template or a target folder) This should NOT be the category definition object!

required
category_name str

name of the category

required

Returns: int: category ID dict: keys are the attribute names. values are sub-dictionaries with the id and type of the attribute.

Example response:
{
    'Status': {
        'id': '12532_2',
        'type': 'String'
    },
    'Legal Approval': {
        'id': '12532_3',
        'type': 'user'
    },
    ...
}
Source code in pyxecm/otcs.py
def get_node_category_definition(
    self, node_id: int, category_name: str
) -> tuple[int, dict]:
    """Get category definition (category id and attribute IDs and types)

    Args:
        node_id (int): node to read the category definition from
                       (e.g. a workspace template or a document template or a target folder)
                       This should NOT be the category definition object!
        category_name (str): name of the category
    Returns:
        int: category ID
        dict: keys are the attribute names. values are sub-dictionaries with the id and type of the attribute.

        Example response:
        {
            'Status': {
                'id': '12532_2',
                'type': 'String'
            },
            'Legal Approval': {
                'id': '12532_3',
                'type': 'user'
            },
            ...
        }
    """

    attribute_definitions = {}
    cat_id = -1

    response = self.get_node_categories(node_id)
    if response and response["results"]:
        for categories in response["results"]:
            keys = categories["metadata"]["categories"].keys()
            cat_id = next((key for key in keys if "_" not in key), -1)
            cat_name = categories["metadata"]["categories"][cat_id]["name"]
            if cat_name != category_name:
                continue
            for att_id in categories["metadata"]["categories"]:
                if not "_" in att_id:
                    continue
                att_name = categories["metadata"]["categories"][att_id]["name"]
                if categories["metadata"]["categories"][att_id]["persona"]:
                    att_type = categories["metadata"]["categories"][att_id][
                        "persona"
                    ]
                else:
                    att_type = categories["metadata"]["categories"][att_id][
                        "type_name"
                    ]
                attribute_definitions[att_name] = {"id": att_id, "type": att_type}
    return cat_id, attribute_definitions

get_node_category_ids(node_id)

Get list of all category definition IDs that are assign to the node.

Parameters:

Name Type Description Default
node_id int

ID of the node to get the categories for.

required

Returns: list: list of category IDs (all categories assigned to the node)

Source code in pyxecm/otcs.py
def get_node_category_ids(self, node_id: int) -> list:
    """Get list of all category definition IDs that are assign to the node.

    Args:
        node_id (int): ID of the node to get the categories for.
    Returns:
        list: list of category IDs (all categories assigned to the node)
    """

    categories = self.get_node_categories(node_id)
    if not categories or not categories["results"]:
        return None

    category_id_list = []

    for category in categories["results"]:
        category_id_list += [
            int(i) for i in category["metadata_order"]["categories"]
        ]

    return category_id_list

get_node_from_nickname(nickname, show_error=False)

Get a node based on the nickname.

Parameters:

Name Type Description Default
nickname str

Nickname of the node.

required
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this nickname is found.

Source code in pyxecm/otcs.py
def get_node_from_nickname(
    self, nickname: str, show_error: bool = False
) -> dict | None:
    """Get a node based on the nickname.

    Args:
        nickname (str): Nickname of the node.
        show_error (bool): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this nickname is found.
    """

    request_url = self.config()["nicknameUrl"] + "/" + nickname + "/nodes"
    request_header = self.request_form_header()

    logger.info(
        "Get node with nickname -> %s; calling -> %s", nickname, request_url
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to get node with nickname -> %s; status -> %s; error -> %s",
                    nickname,
                    response.status_code,
                    response.text,
                )
            else:
                logger.info("Node with nickname -> %s not found.", nickname)
            return None

get_records_management_codes()

Get Records Management Codes. These are the most basic data types of the Records Management configuration and required to create RSIs and other higher-level Records Management configurations

Returns: dict: RM codes or None if the request fails.

Source code in pyxecm/otcs.py
def get_records_management_codes(self) -> dict | None:
    """Get Records Management Codes. These are the most basic data types of
       the Records Management configuration and required to create RSIs and
       other higher-level Records Management configurations

    Args:
        None
    Returns:
        dict: RM codes or None if the request fails.
    """

    request_url = self.config()["recordsManagementUrlv2"] + "/rmcodes"
    request_header = self.request_form_header()

    logger.info("Get list of Records Management codes; calling -> %s", request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            rm_codes_dict = self.parse_request_response(response)
            return rm_codes_dict["results"]["data"]
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get list of Records Management codes; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_records_management_holds()

Get a list of all Records Management Holds in the system. Even though there are folders in the holds management area in RM these are not real folders - they cannot be retrieved with get_node_by_parent_and_name() thus we need this method to get them all.

Returns: dict: Response with list of holds: "results": { "data": { "holds": [ { "HoldID": 0, "HoldName": "string", "ActiveHold": 0, "OBJECT": 0, "ApplyPatron": "string", "DateApplied": "string", "HoldComment": "string", "HoldType": "string", "DateToRemove": "string", "DateRemoved": "string", "RemovalPatron": "string", "RemovalComment": "string", "EditDate": "string", "EditPatron": "string", "AlternateHoldID": 0, "ParentID": 0 } ] } }

Source code in pyxecm/otcs.py
def get_records_management_holds(self) -> dict | None:
    """Get a list of all Records Management Holds in the system. Even though there are folders
    in the holds management area in RM these are not real folders - they cannot be retrieved
    with get_node_by_parent_and_name() thus we need this method to get them all.

    Args:
        None
    Returns:
        dict: Response with list of holds:
        "results": {
            "data": {
                "holds": [
                    {
                        "HoldID": 0,
                        "HoldName": "string",
                        "ActiveHold": 0,
                        "OBJECT": 0,
                        "ApplyPatron": "string",
                        "DateApplied": "string",
                        "HoldComment": "string",
                        "HoldType": "string",
                        "DateToRemove": "string",
                        "DateRemoved": "string",
                        "RemovalPatron": "string",
                        "RemovalComment": "string",
                        "EditDate": "string",
                        "EditPatron": "string",
                        "AlternateHoldID": 0,
                        "ParentID": 0
                    }
                ]
            }
        }
    """

    request_url = self.config()["holdsUrlv2"]

    request_header = self.request_form_header()

    logger.info("Get list of Records Management Holds; calling -> %s", request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get list of Records Management Holds; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_records_management_rsis(limit=100)

Get all Records management RSIs togther with their RSI Schedules.

Parameters:

Name Type Description Default
limit int

max elements to return (default = 100)

100

Returns: list: list of Records Management RSIs or None if the request fails. Each RSI list element is a dict with this structure: { "RSIID": 0, "RSI": "string", "Title": "string", "Subject": "string", "Description": "string", "CreateDate": "string", "RSIStatus": "string", "StatusDate": "string", "DiscontFlag": 0, "DiscontDate": "string", "DiscontComment": "string", "Active": 0, "DispControl": 0, "RSIScheduleID": 0, "RetStage": "string", "RecordType": 0, "EventType": 0, "RSIRuleCode": "string", "DateToUse": "string", "YearEndMonth": 0, "YearEndDay": 0, "RetYears": 0, "RetMonths": 0, "RetDays": 0, "RetIntervals": 0, "EventRuleDate": "string", "EventRule": "string", "EventComment": "string", "StageAction": "string", "FixedRet": 0, "ActionCode": "string", "ActionDescription": "string", "Disposition": "string", "ApprovalFlag": 0, "MaximumRet": 0, "ObjectType": "LIV" }

Source code in pyxecm/otcs.py
def get_records_management_rsis(self, limit: int = 100) -> list | None:
    """Get all Records management RSIs togther with their RSI Schedules.

    Args:
        limit (int, optional): max elements to return (default = 100)
    Returns:
        list: list of Records Management RSIs or None if the request fails.
        Each RSI list element is a dict with this structure:
        {
            "RSIID": 0,
            "RSI": "string",
            "Title": "string",
            "Subject": "string",
            "Description": "string",
            "CreateDate": "string",
            "RSIStatus": "string",
            "StatusDate": "string",
            "DiscontFlag": 0,
            "DiscontDate": "string",
            "DiscontComment": "string",
            "Active": 0,
            "DispControl": 0,
            "RSIScheduleID": 0,
            "RetStage": "string",
            "RecordType": 0,
            "EventType": 0,
            "RSIRuleCode": "string",
            "DateToUse": "string",
            "YearEndMonth": 0,
            "YearEndDay": 0,
            "RetYears": 0,
            "RetMonths": 0,
            "RetDays": 0,
            "RetIntervals": 0,
            "EventRuleDate": "string",
            "EventRule": "string",
            "EventComment": "string",
            "StageAction": "string",
            "FixedRet": 0,
            "ActionCode": "string",
            "ActionDescription": "string",
            "Disposition": "string",
            "ApprovalFlag": 0,
            "MaximumRet": 0,
            "ObjectType": "LIV"
        }
    """

    request_url = self.config()["rsisUrl"] + "?limit=" + str(limit)
    request_header = self.request_form_header()

    logger.info("Get list of Records Management RSIs; calling -> %s", request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            rsi_dict = self.parse_request_response(response)
            return rsi_dict["results"]["data"]["rsis"]
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get list of Records Management RSIs; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_result_value(response, key, index=0, property_name='properties')

Read an item value from the REST API response. This is considering the most typical structures delivered by V2 REST API of Extended ECM. See developer.opentext.com for more details.

Parameters:

Name Type Description Default
response dict

REST API response object

required
key str

key to find (e.g. "id", "name", ...)

required
index int

In case a list of results is delivered the index to use (1st element has index 0). Defaults to 0.

0
property_name str

name of the sub dictionary holding the actual values. Default is "properties".

'properties'

Returns: str: value of the item with the given key for None if no value is found for the given key.

Source code in pyxecm/otcs.py
def get_result_value(
    self,
    response: dict,
    key: str,
    index: int = 0,
    property_name: str = "properties",
) -> str | None:
    """Read an item value from the REST API response. This is considering
       the most typical structures delivered by V2 REST API of Extended ECM.
       See developer.opentext.com for more details.

    Args:
        response (dict): REST API response object
        key (str): key to find (e.g. "id", "name", ...)
        index (int, optional): In case a list of results is delivered the index
                               to use (1st element has index  0). Defaults to 0.
        property_name (str, optional): name of the sub dictionary holding the actual values.
                                       Default is "properties".
    Returns:
        str: value of the item with the given key for None if no value is found for the given key.
    """

    # First do some sanity checks:
    if not response:
        logger.info("Empty REST response - returning None")
        return None
    if not "results" in response:
        logger.error("No 'results' key in REST response - returning None")
        return None

    results = response["results"]
    if not results:
        logger.info("No results found!")
        return None

    # check if results is a list or a dict (both is possible - dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value

        # this is a special treatment for the businessworkspaces REST API - it returns
        # for "Create business workspace" the ID directly in the results dict (without data substructure)
        if key in results:
            return results[key]
        data = results["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data[property_name]
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            properties = data[0][property_name]
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
        logger.debug("Properties of results (dict) -> %s", str(properties))
        # For nearly all OTCS REST Calls perperties is a dict:
        if isinstance(properties, dict):
            if not key in properties:
                logger.error("Key -> %s is not in result properties!", key)
                return None
            return properties[key]
        # but there are some strange ones that have other names for
        # properties and may use a list - see e.g. /v2/holds
        elif isinstance(properties, list):
            if index > len(properties) - 1:
                logger.error(
                    "Illegal Index -> %s given. List has only -> %s elements!",
                    str(index),
                    str(len(properties)),
                )
                return None
            return properties[index][key]
        else:
            logger.error(
                "Properties needs to be a list or dict but it is -> %s",
                str(type(properties)),
            )
            return False
    elif isinstance(results, list):
        # result is a list - we need a valid index:
        if index > len(results) - 1:
            logger.error(
                "Illegal Index -> %s given. List has only -> %s elements!",
                str(index),
                str(len(results)),
            )
            return None
        data = results[index]["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data[property_name]
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            properties = data[0][property_name]
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
        logger.debug(
            "Properties of results (list, index -> %s) -> %s",
            str(index),
            properties,
        )
        if not key in properties:
            logger.error("Key -> %s is not in result properties!", key)
            return None
        return properties[key]
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return None

get_server_info()

Get Content Server information (server info)

Returns: dict: server information or None if the call fails

Example response:
{
    'mobile': {
        'cs_viewer_support': False,
        'offline_use': True
    },
    'server': {
        'advanced_versioning': True,
        'character_encoding': 1,
        'current_date': '2023-09-05T17:09:41',
        'current_locale_suffix': '_en_US',
        'domain_access_enabled': False,
        'enhanced_advanced_versioning': False,
        'force_download_for_mime_types': [...],
        'language_code': 'USA',
        'languages': [...],
        'metadata_languages: [...],
        'url': 'https://otcs.dev.idea-te.eimdemo.com/cs/cs'
        'version': '23.3'
        ...
    },
    'sessions': {
        'enabled': True,
        'expire_after_last_login': False,
        'expire_after_last_request': True,
        'logout_url': '?func=ll.DoLogout&secureRequestToken=LUAQSY%2BJs4KnlwoVgxLtxQFYrov2XefJQM9ShyhOK93Mzp3ymCxX6IGMTtUgNvTH7AYVt%2BbWLEw%3D',
        'session_inactivity': 7020000,
        'session_reaction_time': 180000,
        'session_timeout': 7200000
    },
    'viewer': {
        'content_suite': {...}
    }
}
Source code in pyxecm/otcs.py
def get_server_info(self) -> dict | None:
    """Get Content Server information (server info)

    Args:
        None
    Returns:
        dict: server information or None if the call fails

        Example response:
        {
            'mobile': {
                'cs_viewer_support': False,
                'offline_use': True
            },
            'server': {
                'advanced_versioning': True,
                'character_encoding': 1,
                'current_date': '2023-09-05T17:09:41',
                'current_locale_suffix': '_en_US',
                'domain_access_enabled': False,
                'enhanced_advanced_versioning': False,
                'force_download_for_mime_types': [...],
                'language_code': 'USA',
                'languages': [...],
                'metadata_languages: [...],
                'url': 'https://otcs.dev.idea-te.eimdemo.com/cs/cs'
                'version': '23.3'
                ...
            },
            'sessions': {
                'enabled': True,
                'expire_after_last_login': False,
                'expire_after_last_request': True,
                'logout_url': '?func=ll.DoLogout&secureRequestToken=LUAQSY%2BJs4KnlwoVgxLtxQFYrov2XefJQM9ShyhOK93Mzp3ymCxX6IGMTtUgNvTH7AYVt%2BbWLEw%3D',
                'session_inactivity': 7020000,
                'session_reaction_time': 180000,
                'session_timeout': 7200000
            },
            'viewer': {
                'content_suite': {...}
            }
        }
    """

    request_url = self.config()["serverInfoUrl"]
    request_header = self._cookie

    logger.info(
        "Retrieve Extended ECM server information; calling -> %s", request_url
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to retrieve Extended ECM server information; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_server_version()

Get Content Server version

Returns: str: server version number like 23.4

Source code in pyxecm/otcs.py
def get_server_version(self) -> str | None:
    """Get Content Server version

    Args:
        None
    Returns:
        str: server version number like 23.4
    """

    response = self.get_server_info()
    if not response:
        return None

    server_info = response.get("server")
    if not server_info:
        return None

    return server_info.get("version")

get_subnodes(parent_node_id, filter_node_types=-2, filter_name='', show_hidden=False, limit=100, page=1, fields='properties')

Get a subnodes of a parent node ID.

Parameters:

Name Type Description Default
filter_node_types int

-1 get all containers -2 get all searchable objects (default) -3 get all non-containers

-2
filter_name str

filter nodes for specific name (dfault = no filter)

''
show_hidden bool

list also hidden items (default = False)

False
limit int

maximum number of results (default = 100)

100
page int

number of result page (default = 1 = 1st page)

1
fields str

which fields to retrieve. This can have a big impact on performance!

'properties'

Returns: dict: Subnodes information or None if no node with this parent ID is found.

Source code in pyxecm/otcs.py
def get_subnodes(
    self,
    parent_node_id: int,
    filter_node_types: int = -2,
    filter_name: str = "",
    show_hidden: bool = False,
    limit: int = 100,
    page: int = 1,
    fields: str = "properties",  # per default we just get the most important information
) -> dict | None:
    """Get a subnodes of a parent node ID.

    Args:
        parent_node_id (int) is the node Id of the node
        filter_node_types (int, optional):
            -1 get all containers
            -2 get all searchable objects (default)
            -3 get all non-containers
        filter_name (str, optional): filter nodes for specific name (dfault = no filter)
        show_hidden (bool, optional): list also hidden items (default = False)
        limit (int, optional): maximum number of results (default = 100)
        page (int, optional): number of result page (default = 1 = 1st page)
        fields (str): which fields to retrieve. This can have a big impact on performance!
    Returns:
        dict: Subnodes information or None if no node with this parent ID is found.
    """

    # Add query parameters (these are NOT passed via JSon body!)
    query = {
        "where_type": filter_node_types,
        "limit": limit,
    }
    if filter_name:
        query["where_name"] = filter_name
    if show_hidden:
        query["show_hidden"] = show_hidden
    if page > 1:
        query["page"] = page
    if fields:
        query["fields"] = fields

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(parent_node_id)
        + "/nodes"
        + "?{}".format(encoded_query)
    )
    request_header = self.request_form_header()

    logger.info(
        "Get subnodes of parent node with ID -> %s; calling -> %s",
        str(parent_node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get subnodes for parent node with ID -> %s; status -> %s; error -> %s",
                parent_node_id,
                response.status_code,
                response.text,
            )
            return None

get_unique_names(names, subtype=None)

Get definition information for Unique Names.

Parameters:

Name Type Description Default
names list

list of unique names to lookup.

required
subtype int

filter unique names for those pointing to a specific subtype

None

Returns:

Type Description
dict | None

dict | None: Unique name definition information or None if REST call fails.

dict | None

Example response:

dict | None

{ 'links': {'data': {...}}, 'results': [ { 'NodeId': 13653, 'NodeName': 'Functional Location', 'UniqueName': 'ot_templ_func_location' }, { 'NodeId': 2424, 'NodeName': 'Content Server Document Templates', 'UniqueName': 'Document Templates' } ]

dict | None

}

Source code in pyxecm/otcs.py
def get_unique_names(self, names: list, subtype: int | None = None) -> dict | None:
    """Get definition information for Unique Names.

    Args:
        names (list): list of unique names to lookup.
        subtype (int): filter unique names for those pointing to a specific subtype

    Returns:
        dict | None: Unique name definition information or None if REST call fails.

        Example response:
        {
            'links': {'data': {...}},
            'results': [
                {
                    'NodeId': 13653,
                    'NodeName': 'Functional Location',
                    'UniqueName': 'ot_templ_func_location'
                },
                {
                    'NodeId': 2424,
                    'NodeName': 'Content Server Document Templates',
                    'UniqueName': 'Document Templates'
                }
            ]
        }
    """

    if not names:
        logger.error("Missing Unique Names!")
        return None

    # Add query parameters (these are NOT passed via JSon body!)
    query = {"where_names": "{" + ", ".join(names) + "}"}
    if subtype:
        query["where_subtype"] = subtype

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["uniqueNamesUrl"] + "?{}".format(encoded_query)
    request_header = self.request_form_header()

    if subtype:
        logger.info(
            "Get unique names -> %s with subtype -> %s; calling -> %s",
            str(names),
            str(subtype),
            request_url,
        )
    else:
        logger.info(
            "Get unique names -> %s; calling -> %s",
            str(names),
            request_url,
        )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if subtype:
                logger.warning(
                    "Failed to get unique names -> %s of subtype -> %s; status -> %s; error -> %s",
                    str(names),
                    str(subtype),
                    response.status_code,
                    response.text,
                )
            else:
                logger.warning(
                    "Failed to get unique names -> %s; status -> %s; error -> %s",
                    str(names),
                    response.status_code,
                    response.text,
                )
            return None

get_user(name, show_error=False)

Lookup Extended ECM user based on the name.

Parameters:

Name Type Description Default
name str

name of the user

required
show_error bool

treat as error if user is not found

False

Returns: dict: User information or None if the user is not found. The returned information has a structure like this:

{
    'collection':
    {
        'paging': {...},
        'sorting': {...}
    },
    'links':
    {
        'data': {...}
    },
    'results': [
        {
            'data':
            {
                {
                    'birth_date': None,
                    'business_email': 'pramos@M365x61936377.onmicrosoft.com',
                    'business_fax': None,
                    'business_phone': None,
                    'cell_phone': None,
                    'deleted': False,
                    'display_language': None,
                    'first_name': 'Peter',
                    'gender': None,
                    'group_id': 8006,
                    'home_address_1': None,
                    'home_address_2': None,
                    'home_fax': None,
                    'home_phone': None,
                    'id': 8123,
                    'initials': None,
                    'last_name': 'Ramos',
                    'middle_name': None,
                    'name': 'pramos',
                    'name_formatted': 'Peter Ramos',
                    ...
                    'photo_id': 13981,
                    'photo_url': 'api/v1/members/8123/photo?v=13981.1'
                    ...
                    'type'; 0,
                    'type_name': 'User'
                    }
            }
        }
    ]
}
To access the (login) name of the first user found use ["results"][0]["data"]["properties"]["name"].
It is easier to use the method get_result_value(response, "name", 0)
Source code in pyxecm/otcs.py
def get_user(self, name: str, show_error: bool = False) -> dict | None:
    """Lookup Extended ECM user based on the name.

    Args:
        name (str): name of the user
        show_error (bool): treat as error if user is not found
    Returns:
        dict: User information or None if the user is not found.
        The returned information has a structure like this:

        {
            'collection':
            {
                'paging': {...},
                'sorting': {...}
            },
            'links':
            {
                'data': {...}
            },
            'results': [
                {
                    'data':
                    {
                        {
                            'birth_date': None,
                            'business_email': 'pramos@M365x61936377.onmicrosoft.com',
                            'business_fax': None,
                            'business_phone': None,
                            'cell_phone': None,
                            'deleted': False,
                            'display_language': None,
                            'first_name': 'Peter',
                            'gender': None,
                            'group_id': 8006,
                            'home_address_1': None,
                            'home_address_2': None,
                            'home_fax': None,
                            'home_phone': None,
                            'id': 8123,
                            'initials': None,
                            'last_name': 'Ramos',
                            'middle_name': None,
                            'name': 'pramos',
                            'name_formatted': 'Peter Ramos',
                            ...
                            'photo_id': 13981,
                            'photo_url': 'api/v1/members/8123/photo?v=13981.1'
                            ...
                            'type'; 0,
                            'type_name': 'User'
                            }
                    }
                }
            ]
        }
        To access the (login) name of the first user found use ["results"][0]["data"]["properties"]["name"].
        It is easier to use the method get_result_value(response, "name", 0)
    """

    # Add query parameters (these are NOT passed via JSon body!)
    # type = 0 ==> User
    request_url = self.config()["membersUrlv2"] + "?where_type=0&query={}".format(
        name
    )
    request_header = self.request_form_header()

    logger.info("Get user with name -> %s; calling -> %s", name, request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to get user -> %s; status -> %s; error -> %s",
                    name,
                    response.status_code,
                    response.text,
                )
            else:
                logger.info("User -> %s not found.", name)
            return None

get_user_profile()

Update a defined field for a user profile. IMPORTANT: this method needs to be called by the authenticated user

Parameters:

Name Type Description Default
field str

user profile field

required
value str

new field value

required

Returns: dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).

Source code in pyxecm/otcs.py
def get_user_profile(self) -> dict | None:
    """Update a defined field for a user profile.
       IMPORTANT: this method needs to be called by the authenticated user

    Args:
        field (str): user profile field
        value (str): new field value
    Returns:
        dict: User information or None if the user couldn't be updated
              (e.g. because it doesn't exist).
    """

    request_url = self.config()["membersUrlv2"] + "/preferences"
    request_header = self.request_form_header()

    logger.info(
        "Get profile (settings) for current user; calling -> %s",
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get profile of current user; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_user_proxies(use_v2=False)

Get list of user proxies. This method needs to be called as the user the proxy is acting for. Args: None Returns: dict: Node information or None if REST call fails.

Source code in pyxecm/otcs.py
def get_user_proxies(self, use_v2: bool = False) -> dict | None:
    """Get list of user proxies.
       This method needs to be called as the user the proxy is acting for.
    Args:
        None
    Returns:
        dict: Node information or None if REST call fails.
    """

    if use_v2:
        request_url = self.config()["membersUrlv2"] + "/proxies"
    else:
        request_url = self.config()["membersUrl"] + "/proxies"
    request_header = self.request_form_header()

    logger.info("Get proxy users for current user; calling -> %s", request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get proxy users for current user; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_volume(volume_type, timeout=REQUEST_TIMEOUT)

Get Volume information based on the volume type ID.

Parameters:

Name Type Description Default
volume_type int

ID of the volume type

required
timeout int

timeout for the request in seconds

REQUEST_TIMEOUT

Returns: dict: Volume Details or None if volume is not found. ["results"]["data"]["properties"]["id"] is the node ID of the volume.

Source code in pyxecm/otcs.py
def get_volume(
    self, volume_type: int, timeout: int = REQUEST_TIMEOUT
) -> dict | None:
    """Get Volume information based on the volume type ID.

    Args:
        volume_type (int): ID of the volume type
        timeout (int, optional): timeout for the request in seconds
    Returns:
        dict: Volume Details or None if volume is not found.
        ["results"]["data"]["properties"]["id"] is the node ID of the volume.
    """

    request_url = self.config()["volumeUrl"] + "/" + str(volume_type)
    request_header = self.request_form_header()

    logger.info(
        "Get volume type -> %s; calling -> %s", str(volume_type), request_url
    )

    retries = 0
    while True:
        try:
            response = requests.get(
                url=request_url,
                headers=request_header,
                cookies=self.cookie(),
                timeout=timeout,
            )
            if response.ok:
                return self.parse_request_response(response)
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                logger.warning("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                retries += 1
            else:
                logger.error(
                    "Failed to get volume type -> %s; status -> %s; error -> %s",
                    str(volume_type),
                    response.status_code,
                    response.text,
                )
                return None
        except requests.exceptions.Timeout:
            if retries <= REQUEST_MAX_RETRIES:
                logger.warning(
                    "Request timed out. Retrying in %s seconds...",
                    str(REQUEST_RETRY_DELAY),
                )
                retries += 1
                time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
            else:
                logger.error(
                    "Failed to get volume type -> %s; timeout error",
                    str(volume_type),
                )
                # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                logger.warning("Turn timeouts off and wait forever...")
                timeout = None

get_volumes()

Get all Volumes.

Returns: dict: Volume Details or None if an error occured. { 'links': { 'data': {...} }, 'results': [ { 'data': { 'properties': { 'advanced_versioning': None, 'container': True, 'container_size': 16, 'create_date': '2023-05-07T23:18:50Z', 'create_user_id': 1000, 'description': '', 'description_multilingual': {'de': '', 'en': '', 'fr': '', 'it': '', 'ja': ''}, 'external_create_date': None, 'external_identity': '', 'external_identity_type': '', 'external_modify_date': None, 'external_source': '', 'favorite': False, 'hidden': False, ... 'id': 2000, ... 'name': 'Enterprise', 'name_multilingual': {'de': '', 'en': 'Enterprise', 'fr': '', 'it': '', 'ja': ''}, ... 'parent_id': -1, 'type': 141, 'volume_id': -2000, ... } ... } }, ... ] } Example: ["results"][0]["data"]["properties"]["id"] is the node ID of the volume.

Source code in pyxecm/otcs.py
def get_volumes(self) -> dict | None:
    """Get all Volumes.

    Args:
        None
    Returns:
        dict: Volume Details or None if an error occured.
        {
            'links': {
                'data': {...}
            },
            'results': [
                {
                    'data': {
                        'properties': {
                            'advanced_versioning': None,
                            'container': True,
                            'container_size': 16,
                            'create_date': '2023-05-07T23:18:50Z',
                            'create_user_id': 1000,
                            'description': '',
                            'description_multilingual': {'de': '', 'en': '', 'fr': '', 'it': '', 'ja': ''},
                            'external_create_date': None,
                            'external_identity': '',
                            'external_identity_type': '',
                            'external_modify_date': None,
                            'external_source': '',
                            'favorite': False,
                            'hidden': False,
                            ...
                            'id': 2000,
                            ...
                            'name': 'Enterprise',
                            'name_multilingual': {'de': '', 'en': 'Enterprise', 'fr': '', 'it': '', 'ja': ''},
                            ...
                            'parent_id': -1,
                            'type': 141,
                            'volume_id': -2000,
                            ...
                        }
                        ...
                    }
                },
                ...
            ]
        }
        Example:
        ["results"][0]["data"]["properties"]["id"] is the node ID of the volume.
    """

    request_url = self.config()["volumeUrl"]
    request_header = self.request_form_header()

    logger.info("Get volumes; calling -> %s", request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get volumes; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

get_web_report_parameters(nickname)

Get parameters of a Web Report in Extended ECM. These are defined on the Web Report node (Properties --> Parameters)

Parameters:

Name Type Description Default
nickname str

Nickname of the Web Reports node.

required

Returns: Response: List of Web Report parameters. Each list item is a dict describing the parameter. Structure of the list items: { "type": "string", "parm_name": "string", "display_text": "string", "prompt": true, "prompt_order": 0, "default_value": null, "description": "string", "mandatory": true } None if the REST call has failed.

Source code in pyxecm/otcs.py
def get_web_report_parameters(self, nickname: str):
    """Get parameters of a Web Report in Extended ECM. These are defined on the Web Report node
        (Properties --> Parameters)

    Args:
        nickname (str): Nickname of the Web Reports node.
    Returns:
        Response: List of Web Report parameters. Each list item is a dict describing the parameter.
        Structure of the list items:
        {
            "type": "string",
            "parm_name": "string",
            "display_text": "string",
            "prompt": true,
            "prompt_order": 0,
            "default_value": null,
            "description": "string",
            "mandatory": true
        }
        None if the REST call has failed.
    """

    request_url = self.config()["webReportsUrl"] + "/" + nickname + "/parameters"
    request_header = self.request_form_header()

    logger.info(
        "Retrieving parameters of Web Report with nickname -> %s; calling -> %s",
        nickname,
        request_url,
    )
    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            # Return the "data" element which is a list of dict items:
            result_dict = self.parse_request_response(response)
            logger.debug("Web Report parameters result -> %s", str(result_dict))
            if not result_dict.get("data"):
                return None
            return result_dict["data"]
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to retrieve parameters of Web Report with nickname -> %s; status -> %s; error -> %s",
                nickname,
                response.status_code,
                response.text,
            )
            return None

get_workspace(node_id)

Get a workspace based on the node ID.

Parameters:

Name Type Description Default
node_id int

Node ID of the workspace to retrieve.

required

Returns: dict: Workspace node information or None if no node with this ID is found.

Example response:
{
    'links': {
        'data': {...}
    },
    'meta_data': {
        'properties': {...}
    },
    'paging': {
        'limit': 500,
        'page': 1,
        'page_total': 1,
        'range_max': 1,
        'range_min': 1,
        'total_count': 1
    },
    'results': [
        {
            'actions': {...},
            'data': {
                'business_properties': {
                    'business_object_id': '000004000240',
                    'business_object_type': 'BUS2007',
                    'business_object_type_id': 18,
                    'business_object_type_name': 'Maintenance Order',
                    'business_object_type_name_multilingual': {...},
                    'display_url': "https://fiori.qa.idea-te.eimdemo.com:8443/sap/bc/ui2/flp#MaintenanceOrder-displayXecmFactSheet&//C_ObjPgMaintOrder('000004000240')",
                    'external_system_id': 'TM6',
                    'external_system_name': 'TM6',
                    'has_default_display': True,
                    'has_default_search': True,
                    'isEarly': False,
                    'workspace_type_id': 42,
                    'workspace_type_name': 'Maintenance Order',
                    'workspace_type_name_multilingual': {},
                    ...
                }
                'properties': {
                    'volume_id': -2000,
                    'id': 36780,
                    'parent_id': 13567,
                    'owner_user_id': 7240,
                    'name': '4600000044 - C.E.B. New York Inc.',
                    'type': 848,
                    'description': '',
                    'create_date': '2023-09-02T11:07:06',
                    'create_user_id': 7240,
                    'create_user_id': 7240,
                    'modify_date': '2023-09-02T11:07:11',
                    'modify_user_id': 7240,
                    'reserved': False,
                    'reserved_user_id': 0,
                    'reserved_date': None,
                    'order': None,
                    'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                    'hidden': False,
                    'mime_type': None,
                    'original_id': 0,
                    'wnf_wksp_type_id': 16,
                    'wnf_wksp_template_id': 15615,
                    'size_formatted': '7 Items',
                    'type_name': 'Business Workspace',
                    'container': True,
                    'size': 7,
                    ...
                }
                'wksp_info':
                {
                    'wksp_type_icon': '/appimg/ot_bws/icons/16634%2Esvg?v=161194_13949'
                }
            },
            'metadata': {...},
            'metadata_order': {...}
        }
    ],
    'wksp_info': {
        'wksp_type_icon': None
    }
    'workspace_references': [
        {
            'business_object_id': '000004000240',
            'business_object_type': 'BUS2007',
            'business_object_type_id': 18,
            'external_system_id': 'TM6',
            'has_default_display': True,
            'has_default_search': True,
            'workspace_type_id': 42
        }
    ]
}
Source code in pyxecm/otcs.py
def get_workspace(self, node_id: int) -> dict | None:
    """Get a workspace based on the node ID.

    Args:
        node_id (int): Node ID of the workspace to retrieve.
    Returns:
        dict: Workspace node information or None if no node with this ID is found.

        Example response:
        {
            'links': {
                'data': {...}
            },
            'meta_data': {
                'properties': {...}
            },
            'paging': {
                'limit': 500,
                'page': 1,
                'page_total': 1,
                'range_max': 1,
                'range_min': 1,
                'total_count': 1
            },
            'results': [
                {
                    'actions': {...},
                    'data': {
                        'business_properties': {
                            'business_object_id': '000004000240',
                            'business_object_type': 'BUS2007',
                            'business_object_type_id': 18,
                            'business_object_type_name': 'Maintenance Order',
                            'business_object_type_name_multilingual': {...},
                            'display_url': "https://fiori.qa.idea-te.eimdemo.com:8443/sap/bc/ui2/flp#MaintenanceOrder-displayXecmFactSheet&//C_ObjPgMaintOrder('000004000240')",
                            'external_system_id': 'TM6',
                            'external_system_name': 'TM6',
                            'has_default_display': True,
                            'has_default_search': True,
                            'isEarly': False,
                            'workspace_type_id': 42,
                            'workspace_type_name': 'Maintenance Order',
                            'workspace_type_name_multilingual': {},
                            ...
                        }
                        'properties': {
                            'volume_id': -2000,
                            'id': 36780,
                            'parent_id': 13567,
                            'owner_user_id': 7240,
                            'name': '4600000044 - C.E.B. New York Inc.',
                            'type': 848,
                            'description': '',
                            'create_date': '2023-09-02T11:07:06',
                            'create_user_id': 7240,
                            'create_user_id': 7240,
                            'modify_date': '2023-09-02T11:07:11',
                            'modify_user_id': 7240,
                            'reserved': False,
                            'reserved_user_id': 0,
                            'reserved_date': None,
                            'order': None,
                            'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                            'hidden': False,
                            'mime_type': None,
                            'original_id': 0,
                            'wnf_wksp_type_id': 16,
                            'wnf_wksp_template_id': 15615,
                            'size_formatted': '7 Items',
                            'type_name': 'Business Workspace',
                            'container': True,
                            'size': 7,
                            ...
                        }
                        'wksp_info':
                        {
                            'wksp_type_icon': '/appimg/ot_bws/icons/16634%2Esvg?v=161194_13949'
                        }
                    },
                    'metadata': {...},
                    'metadata_order': {...}
                }
            ],
            'wksp_info': {
                'wksp_type_icon': None
            }
            'workspace_references': [
                {
                    'business_object_id': '000004000240',
                    'business_object_type': 'BUS2007',
                    'business_object_type_id': 18,
                    'external_system_id': 'TM6',
                    'has_default_display': True,
                    'has_default_search': True,
                    'workspace_type_id': 42
                }
            ]
        }
    """

    request_url = self.config()["businessWorkspacesUrl"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.info(
        "Get workspace with ID -> %s; calling -> %s", str(node_id), request_url
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get workspace with ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

get_workspace_by_business_object(external_system_name, business_object_type, business_object_id, return_workspace_metadata=False, show_error=False)

Get a workspace based on the business object of an external system.

Parameters:

Name Type Description Default
external_system_name str

Name of the connection

required
business_object_type str

Type of the Business object, e.g. KNA1 for SAP customers

required
business_object_id str

ID of the business object in the external system

required
return_workspace_metadata bool

Whether or not workspace metadata (categories) should be returned. Default is False.

False
show_error bool

Treat as error if node is not found. Default is False.

False

Returns: dict: Workspace node information or None if no node with this ID is found.

Example response:
{
    'links': {
        'data': {...}
    },
    'meta_data': {
        'properties': {...}
    },
    'paging': {
        'limit': 500,
        'page': 1,
        'page_total': 1,
        'range_max': 1,
        'range_min': 1,
        'total_count': 1
    },
    'results': [
        {
            'actions': {...},
            'data': {
                'properties': {
                    'volume_id': -2000,
                    'id': 36780,
                    'parent_id': 13567,
                    'owner_user_id': 7240,
                    'name': '4600000044 - C.E.B. New York Inc.',
                    'type': 848,
                    'description': '',
                    'create_date': '2023-09-02T11:07:06',
                    'create_user_id': 7240,
                    'create_user_id': 7240,
                    'modify_date': '2023-09-02T11:07:11',
                    'modify_user_id': 7240,
                    'reserved': False,
                    'reserved_user_id': 0,
                    'reserved_date': None,
                    'order': None,
                    'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                    'hidden': False,
                    'mime_type': None,
                    'original_id': 0,
                    'wnf_wksp_type_id': 16,
                    'wnf_wksp_template_id': 15615,
                    'size_formatted': '7 Items',
                    'type_name': 'Business Workspace',
                    'container': True,
                    'size': 7,
                    ...
                }
            },
            'metadata': {...},
            'metadata_order': {...}
        }
    ],
    'wksp_info': {
        'wksp_type_icon': None
    }
}
Source code in pyxecm/otcs.py
def get_workspace_by_business_object(
    self,
    external_system_name: str,
    business_object_type: str,
    business_object_id: str,
    return_workspace_metadata: bool = False,
    show_error: bool = False,
) -> dict | None:
    """Get a workspace based on the business object of an external system.

    Args:
        external_system_name (str): Name of the connection
        business_object_type (str): Type of the Business object, e.g. KNA1 for SAP customers
        business_object_id (str): ID of the business object in the external system
        return_workspace_metadata (bool, optional): Whether or not workspace metadata (categories) should be returned.
                                                    Default is False.
        show_error (bool, optional): Treat as error if node is not found. Default is False.
    Returns:
        dict: Workspace node information or None if no node with this ID is found.

        Example response:
        {
            'links': {
                'data': {...}
            },
            'meta_data': {
                'properties': {...}
            },
            'paging': {
                'limit': 500,
                'page': 1,
                'page_total': 1,
                'range_max': 1,
                'range_min': 1,
                'total_count': 1
            },
            'results': [
                {
                    'actions': {...},
                    'data': {
                        'properties': {
                            'volume_id': -2000,
                            'id': 36780,
                            'parent_id': 13567,
                            'owner_user_id': 7240,
                            'name': '4600000044 - C.E.B. New York Inc.',
                            'type': 848,
                            'description': '',
                            'create_date': '2023-09-02T11:07:06',
                            'create_user_id': 7240,
                            'create_user_id': 7240,
                            'modify_date': '2023-09-02T11:07:11',
                            'modify_user_id': 7240,
                            'reserved': False,
                            'reserved_user_id': 0,
                            'reserved_date': None,
                            'order': None,
                            'icon': '/cssupport/otsapxecm/wksp_contract_vendor.png',
                            'hidden': False,
                            'mime_type': None,
                            'original_id': 0,
                            'wnf_wksp_type_id': 16,
                            'wnf_wksp_template_id': 15615,
                            'size_formatted': '7 Items',
                            'type_name': 'Business Workspace',
                            'container': True,
                            'size': 7,
                            ...
                        }
                    },
                    'metadata': {...},
                    'metadata_order': {...}
                }
            ],
            'wksp_info': {
                'wksp_type_icon': None
            }
        }
    """

    request_url = (
        self.config()["externalSystemUrl"]
        + "/"
        + external_system_name
        + "/botypes/"
        + business_object_type
        + "/boids/"
        + business_object_id
    )
    if return_workspace_metadata:
        request_url += "?metadata"

    request_header = self.request_form_header()

    logger.info(
        "Get workspace via external system -> %s (Business Object Type -> %s; Business Object ID -> %s); calling -> %s",
        external_system_name,
        business_object_type,
        business_object_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to get workspace via external system -> %s (Business Object Type -> %s; Business Object ID -> %s); status -> %s; error -> %s",
                    external_system_name,
                    business_object_type,
                    business_object_id,
                    response.status_code,
                    response.text,
                )
            else:
                logger.info(
                    "Cannot fing workspace via external system -> %s (Business Object Type -> %s; Business Object ID -> %s); status -> %s; error -> %s",
                    external_system_name,
                    business_object_type,
                    business_object_id,
                    response.status_code,
                    response.text,
                )
            return None

get_workspace_by_type_and_name(type_name='', type_id=None, name='', expanded_view=True)

Lookup workspace based on workspace type and workspace name.

Parameters:

Name Type Description Default
type_name str

name of the workspace type

''
type_id int

ID of the workspace_type

None
name str

Name of the workspace, if "" then deliver all instances of the given workspace type.

''
expanded_view bool

If 'False' then just search in recently accessed business workspace for this name and type. If 'True' (this is the default) then search in all workspaces for this name and type.

True

Returns: dict: Workspace information or None if the workspace is not found.

Source code in pyxecm/otcs.py
def get_workspace_by_type_and_name(
    self,
    type_name: str = "",
    type_id: int = None,
    name: str = "",
    expanded_view: bool = True,
) -> dict | None:
    """Lookup workspace based on workspace type and workspace name.

    Args:
        type_name (str, optional): name of the workspace type
        type_id (int, optional): ID of the workspace_type
        name (str, optional): Name of the workspace, if "" then deliver all instances
                              of the given workspace type.
        expanded_view (bool, optional): If 'False' then just search in recently
                                        accessed business workspace for this name and type.
                                        If 'True' (this is the default) then search in all
                                        workspaces for this name and type.
    Returns:
        dict: Workspace information or None if the workspace is not found.
    """

    # Add query parameters (these are NOT passed via JSon body!)
    query = {
        "expanded_view": expanded_view,
    }
    if type_name:
        query["where_workspace_type_name"] = type_name
    if type_id:
        query["where_workspace_type_id"] = type_id
    if name:
        query["where_name"] = name

    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["businessWorkspacesUrl"] + "?{}".format(
        encoded_query
    )
    request_header = self.request_form_header()

    if name:
        logger.info(
            "Get workspace with name -> %s and type -> %s; calling -> %s",
            name,
            type_name,
            request_url,
        )
    else:
        logger.info(
            "Get all workspace instances of type -> %s; calling -> %s",
            type_name,
            request_url,
        )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if name:
                logger.warning(
                    "Failed to get workspace -> %s of type -> %s; status -> %s; error -> %s",
                    name,
                    type_name,
                    response.status_code,
                    response.text,
                )
            else:
                logger.warning(
                    "Failed to get workspace instances of type -> %s; status -> %s; error -> %s",
                    type_name,
                    response.status_code,
                    response.text,
                )
            return None

get_workspace_create_form(template_id, external_system_id=None, bo_type=None, bo_id=None, parent_id=None)

Get the Workspace create form.

Parameters:

Name Type Description Default
template_id int

ID of the workspace template

required
external_system_id int

Identifier of the external system (None if no external system)

None
bo_type int

Business object type (None if no external system)

None
bo_id int

Business object identifier / key (None if no external system)

None
parent_id int

Parent ID of the workspaces. Needs only be specified in special cases where workspace location cannot be derived from workspace type definition, e.g. sub-workspace

None

Returns: dict: Workspace Create Form data or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_create_form(
    self,
    template_id: int,
    external_system_id: int = None,
    bo_type: int = None,
    bo_id: int = None,
    parent_id: int = None,
) -> dict | None:
    """Get the Workspace create form.

    Args:
        template_id (int): ID of the workspace template
        external_system_id (int, optional): Identifier of the external system (None if no external system)
        bo_type (int, optional): Business object type (None if no external system)
        bo_id (int, optional): Business object identifier / key (None if no external system)
        parent_id (int, optional): Parent ID of the workspaces. Needs only be specified in special
                                   cases where workspace location cannot be derived from workspace
                                   type definition, e.g. sub-workspace
    Returns:
        dict: Workspace Create Form data or None if the request fails.
    """

    request_url = self.config()[
        "businessworkspacecreateform"
    ] + "?template_id={}".format(template_id)
    # Is a parent ID specifified? Then we need to add it to the request URL
    if parent_id is not None:
        request_url += "&parent_id={}".format(parent_id)
    # Is this workspace connected to a business application / external system?
    if external_system_id and bo_type and bo_id:
        request_url += "&ext_system_id={}".format(external_system_id)
        request_url += "&bo_type={}".format(bo_type)
        request_url += "&bo_id={}".format(bo_id)
        logger.info(
            "Include business object connection -> (%s, %s, %s) in workspace create form...",
            str(external_system_id),
            str(bo_type),
            str(bo_id),
        )
    request_header = self.request_form_header()

    logger.info(
        "Get workspace create form for workspace template ID -> %s; calling -> %s",
        str(template_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get workspace create form for template -> %s; status -> %s; error -> %s",
                str(template_id),
                response.status_code,
                response.text,
            )
            return None

get_workspace_instances(type_name='', type_id=None, expanded_view=True)

Get all workspace instances of a given type. This is a convenience wrapper method for get_workspace_by_type_and_name()

Parameters:

Name Type Description Default
type_name str

Name of the workspace type

''
type_id int

ID of the workspace_type

None
expanded_view bool

If 'False' then just search in recently accessed business workspace for this name and type. If 'True' (this is the default) then search in all workspaces for this name and type.

True

Returns: dict: Workspace information or None if the workspace is not found.

Source code in pyxecm/otcs.py
def get_workspace_instances(
    self, type_name: str = "", type_id: int = None, expanded_view: bool = True
):
    """Get all workspace instances of a given type. This is a convenience
       wrapper method for get_workspace_by_type_and_name()

    Args:
        type_name (str, optional): Name of the workspace type
        type_id (int, optional): ID of the workspace_type
        expanded_view (bool, optional): If 'False' then just search in recently
                                        accessed business workspace for this name and type.
                                        If 'True' (this is the default) then search in all
                                        workspaces for this name and type.
    Returns:
        dict: Workspace information or None if the workspace is not found.
    """

    # Omitting the name lets it return all instances of the type:
    return self.get_workspace_by_type_and_name(
        type_name=type_name, type_id=type_id, name="", expanded_view=expanded_view
    )

get_workspace_relationships(workspace_id)

Get the Workspace relationships to other workspaces.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace template

required

Returns: dict: Workspace relationships or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_relationships(self, workspace_id: int) -> dict | None:
    """Get the Workspace relationships to other workspaces.

    Args:
        workspace_id (int): ID of the workspace template
    Returns:
        dict: Workspace relationships or None if the request fails.
    """

    request_url = (
        self.config()["businessWorkspacesUrl"]
        + "/"
        + str(workspace_id)
        + "/relateditems"
    )
    request_header = self.request_form_header()

    logger.info(
        "Get related workspaces for workspace with ID -> %s; calling -> %s",
        str(workspace_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get related workspaces of workspace with ID -> %s; status -> %s; error -> %s",
                str(workspace_id),
                response.status_code,
                response.text,
            )
            return None

get_workspace_roles(workspace_id)

Get the Workspace roles.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace template

required

Returns: dict: Workspace Roles data or None if the request fails.

Source code in pyxecm/otcs.py
def get_workspace_roles(self, workspace_id: int) -> dict | None:
    """Get the Workspace roles.

    Args:
        workspace_id (int): ID of the workspace template
    Returns:
        dict: Workspace Roles data or None if the request fails.
    """

    request_url = (
        self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/roles"
    )
    request_header = self.request_form_header()

    logger.info(
        "Get workspace roles of workspace with ID -> %s; calling -> %s",
        str(workspace_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get roles of workspace with ID -> %s; status -> %s; error -> %s",
                str(workspace_id),
                response.status_code,
                response.text,
            )
            return None

get_workspace_types(expand_workspace_info=True, expand_templates=True)

Get all workspace types configured in Extended ECM.

Parameters:

Name Type Description Default
expand_workspace_info bool

Controls if the workspace info is returned as well

True
expand_workspace_info bool

Controls if the list of workspace templates per workspace typ is returned as well

True

Returns: dict: Workspace Types or None if the request fails.

Example response:
{
    'links': {
        'data': {...}
    },
    'results': [
        {
            'data': {
                'properties': {
                    'rm_enabled': False,
                    'templates': [
                        {
                            'id': 14471,
                            'name': 'Campaign',
                            'subtype': 848
                        },
                        ...
                    ],
                    'wksp_type_id': 35,
                    'wksp_type_name': 'Campaign'
                },
                'wksp_info': {
                    'wksp_type_icon': '/appimg/ot_bws/icons/13147%2Esvg?v=161108_84584'
                }
            }
        }
    ]
}
Source code in pyxecm/otcs.py
def get_workspace_types(
    self, expand_workspace_info: bool = True, expand_templates: bool = True
) -> dict | None:
    """Get all workspace types configured in Extended ECM.

    Args:
        expand_workspace_info (bool, optional): Controls if the workspace info
                                                is returned as well
        expand_workspace_info (bool, optional): Controls if the list of workspace templates
                                                per workspace typ is returned as well
    Returns:
        dict: Workspace Types or None if the request fails.

        Example response:
        {
            'links': {
                'data': {...}
            },
            'results': [
                {
                    'data': {
                        'properties': {
                            'rm_enabled': False,
                            'templates': [
                                {
                                    'id': 14471,
                                    'name': 'Campaign',
                                    'subtype': 848
                                },
                                ...
                            ],
                            'wksp_type_id': 35,
                            'wksp_type_name': 'Campaign'
                        },
                        'wksp_info': {
                            'wksp_type_icon': '/appimg/ot_bws/icons/13147%2Esvg?v=161108_84584'
                        }
                    }
                }
            ]
        }
    """

    request_url = self.config()["businessWorkspaceTypesUrl"]
    if expand_templates:
        request_url += "?expand_templates=true"
    else:
        request_url += "?expand_templates=false"
    if expand_workspace_info:
        request_url += "&expand_wksp_info=true"
    else:
        request_url += "&expand_wksp_info=false"

    request_header = self.request_form_header()

    logger.info("Get workspace types; calling -> %s", request_url)

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to get workspace types; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

hostname()

Returns the hostname of Extended ECM (e.g. "otcs")

Returns:

Name Type Description
str str

hostname

Source code in pyxecm/otcs.py
def hostname(self) -> str:
    """Returns the hostname of Extended ECM (e.g. "otcs")

    Returns:
        str: hostname
    """
    return self.config()["hostname"]

import_physical_objects_codes(file_path, update_existing_codes=True)

Import Physical Objects codes from a config file that is uploaded from the Python pod Args: file_path (str): path + filename of config file in Python container filesystem update_existing_codes (bool): whether or not existing codes should be updated (default = True) Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_physical_objects_codes(
    self, file_path: str, update_existing_codes: bool = True
) -> bool:
    """Import Physical Objects codes from a config file that is uploaded from the Python pod
    Args:
        file_path (str): path + filename of config file in Python container filesystem
        update_existing_codes (bool): whether or not existing codes should be updated (default = True)
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["physicalObjectsUrl"] + "/importCodes"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Physical Objects Codes from file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {"updateExistingCodes": update_existing_codes}

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=settings_post_data,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Physical Objects Codes from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

import_physical_objects_locators(file_path)

Import Physical Objects locators from a config file that is uploaded from the python pod Args: file_path (str): path + filename of config file in Python container filesystem Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_physical_objects_locators(self, file_path: str) -> bool:
    """Import Physical Objects locators from a config file that is uploaded from the python pod
    Args:
        file_path (str): path + filename of config file in Python container filesystem
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["physicalObjectsUrl"] + "/importLocators"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Physical Objects Locators from file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Physical Objects Locators from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

import_physical_objects_settings(file_path)

Import Physical Objects settings from a config file that is uploaded from the python pod Args: file_path (str): path + filename of config file in Python container filesystem Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_physical_objects_settings(self, file_path: str) -> bool:
    """Import Physical Objects settings from a config file that is uploaded from the python pod
    Args:
        file_path (str): path + filename of config file in Python container filesystem
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["physicalObjectsUrl"] + "/importSettings"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Physical Objects Settings from server file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Physical Objects settings from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

import_records_management_codes(file_path, update_existing_codes=True)

Import RM Codes from a file that is uploaded from the python pod Args: file_path (str): path + filename of settings file in Python container filesystem update_existing_codes (bool): Flag that controls whether existing table maintenance codes should be updated. Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_records_management_codes(
    self, file_path: str, update_existing_codes: bool = True
) -> bool:
    """Import RM Codes from a file that is uploaded from the python pod
    Args:
        file_path (str): path + filename of settings file in Python container filesystem
        update_existing_codes (bool): Flag that controls whether existing table maintenance codes
                                      should be updated.
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["recordsManagementUrl"] + "/importCodes"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Records Management Codes from file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {"updateExistingCodes": update_existing_codes}

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=settings_post_data,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Records Management Codes from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

import_records_management_rsis(file_path, update_existing_rsis=True, delete_schedules=False)

Import RM RSIs from a config file that is uploaded from the Python pod Args: file_path (str): path + filename of config file in Python container filesystem update_existing_rsis (bool, optional): whether or not existing RSIs should be updated (or ignored) delete_schedules (bool, optional): whether RSI Schedules should be deleted Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_records_management_rsis(
    self,
    file_path: str,
    update_existing_rsis: bool = True,
    delete_schedules: bool = False,
) -> bool:
    """Import RM RSIs from a config file that is uploaded from the Python pod
    Args:
        file_path (str): path + filename of config file in Python container filesystem
        update_existing_rsis (bool, optional): whether or not existing RSIs should be updated (or ignored)
        delete_schedules (bool, optional): whether RSI Schedules should be deleted
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["recordsManagementUrl"] + "/importRSIs"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Records Management RSIs from file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {
        "updateExistingRSIs": update_existing_rsis,
        "deleteSchedules": delete_schedules,
    }

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=settings_post_data,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Records Management RSIs from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

import_records_management_settings(file_path)

Import Records Management settings from a file that is uploaded from the python pod

Parameters:

Name Type Description Default
file_path str

path + filename of config file in Python container filesystem

required

Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_records_management_settings(self, file_path: str) -> bool:
    """Import Records Management settings from a file that is uploaded from the python pod

    Args:
        file_path (str): path + filename of config file in Python container filesystem
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["recordsManagementUrl"] + "/importSettings"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Records Management Settings from file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Records Management Settings from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

import_security_clearance_codes(file_path, include_users=False)

Import Security Clearance codes from a config file that is uploaded from the python pod Args: file_path (str): path + filename of config file in Python container filesystem include_users (bool): defines if users should be included or not Returns: bool: True if if the REST call succeeds or False otherwise.

Source code in pyxecm/otcs.py
def import_security_clearance_codes(
    self, file_path: str, include_users: bool = False
) -> bool:
    """Import Security Clearance codes from a config file that is uploaded from the python pod
    Args:
        file_path (str): path + filename of config file in Python container filesystem
        include_users (bool): defines if users should be included or not
    Returns:
        bool: True if if the REST call succeeds or False otherwise.
    """

    request_url = self.config()["securityClearancesUrl"] + "/importCodes"

    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 400 response

    logger.info(
        "Importing Security Clearance Codes from file -> %s; calling -> %s",
        file_path,
        request_url,
    )

    settings_post_data = {"includeusers": include_users}

    filename = os.path.basename(file_path)
    if not os.path.exists(file_path):
        logger.error(
            "The file -> %s does not exist in path -> %s!",
            filename,
            os.path.dirname(file_path),
        )
        return False
    settings_post_file = {
        "file": (filename, open(file=file_path, encoding="utf-8"), "text/xml")
    }

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=settings_post_data,
            files=settings_post_file,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return True
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to import Security Clearance Codes from file -> %s; status -> %s; error -> %s",
                file_path,
                response.status_code,
                response.text,
            )
            return False

install_cs_application(application_name)

Install a CS Application (based on WebReports)

Parameters:

Name Type Description Default
application_name str

name of the application (e.g. OTPOReports, OTRMReports, OTRMSecReports)

required

Returns: dict: Response or None if the installation of the CS Application has failed.

Source code in pyxecm/otcs.py
def install_cs_application(self, application_name: str) -> dict | None:
    """Install a CS Application (based on WebReports)

    Args:
        application_name (str): name of the application (e.g. OTPOReports, OTRMReports, OTRMSecReports)
    Returns:
        dict: Response or None if the installation of the CS Application has failed.
    """

    install_cs_application_post_data = {"appName": application_name}

    request_url = self.config()["csApplicationsUrl"] + "/install"
    request_header = self.request_form_header()

    logger.info(
        "Install CS Application -> %s; calling -> %s", application_name, request_url
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=install_cs_application_post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to install CS Application -> %s; status -> %s; error -> %s",
                application_name,
                response.status_code,
                response.text,
            )
            return None

is_configured()

Checks if the Content Server pod is configured to receive requests.

Returns: bool: True if pod is ready. False if pod is not yet ready.

Source code in pyxecm/otcs.py
def is_configured(self) -> bool:
    """Checks if the Content Server pod is configured to receive requests.

    Args:
        None.
    Returns:
        bool: True if pod is ready. False if pod is not yet ready.
    """

    request_url = self.config()["configuredUrl"]

    logger.info("Trying to retrieve OTCS URL -> %s", request_url)

    try:
        response = requests.get(
            url=request_url,
            headers=REQUEST_JSON_HEADERS,
            timeout=REQUEST_TIMEOUT,
        )
    except requests.exceptions.RequestException as exception:
        logger.warning(
            "Unable to connect to -> %s; warning -> %s",
            request_url,
            exception.strerror,
        )
        logger.warning("OTCS service may not be ready yet.")
        return False

    if not response.ok:
        logger.warning(
            "Unable to connect to -> %s; status -> %s; warning -> %s",
            request_url,
            response.status_code,
            response.text,
        )
        return False

    return True

is_proxy(user_name)

Check if a user is defined as proxy of the current user. This method differentiates between the old (xGov) based implementation and the new Extended ECM platform one that was introduced with version 23.4.

Parameters:

Name Type Description Default
user_name str

user to test (login name)

required

Returns: bool: True is user is proxy of current user. False if not.

Source code in pyxecm/otcs.py
def is_proxy(self, user_name: str) -> bool:
    """Check if a user is defined as proxy of the current user.
       This method differentiates between the old (xGov) based
       implementation and the new Extended ECM platform one
       that was introduced with version 23.4.

    Args:
        user_name (str): user  to test (login name)
    Returns:
        bool: True is user is proxy of current user. False if not.
    """

    version_number = self.get_server_version()
    # Split the version number by dot
    parts = version_number.split(".")
    # Take the first two parts and join them back with a dot
    stripped_version = ".".join(parts[:2])

    try:
        version_number = float(stripped_version)
    except ValueError:
        version_number = 99.99  # Set to version 99.99 for "main"

    if version_number >= 23.4:
        response = self.get_user_proxies(use_v2=True)
        if self.exist_result_item(
            response=response, key="name", value=user_name, property_name=""
        ):
            return True
        else:
            return False
    else:
        response = self.get_user_proxies(use_v2=False)
        if not response or not "proxies" in response:
            return False
        proxies = response["proxies"]

        for proxy in proxies:
            if proxy["name"] == user_name:
                return True
        return False

is_ready()

Checks if the Content Server pod is ready to receive requests.

Returns: bool: True if pod is ready. False if pod is not yet ready.

Source code in pyxecm/otcs.py
def is_ready(self) -> bool:
    """Checks if the Content Server pod is ready to receive requests.

    Args:
        None.
    Returns:
        bool: True if pod is ready. False if pod is not yet ready.
    """

    request_url = self.config()["isReady"]

    logger.info("Trying to retrieve OTCS URL -> %s", request_url)

    try:
        response = requests.get(
            url=request_url,
            headers=REQUEST_JSON_HEADERS,
            timeout=2,
        )
    except requests.exceptions.RequestException as exception:
        logger.warning(
            "Unable to connect to -> %s; warning -> %s",
            request_url,
            exception.strerror,
        )
        logger.warning("OTCS service may not be ready yet.")
        return False

    if not response.status_code == 200:
        logger.warning(
            "Unable to connect to -> %s; status -> %s; warning -> %s",
            request_url,
            response.status_code,
            response.text,
        )
        return False

    return True

lookup_result_value(response, key, value, return_key)

Lookup a property value based on a provided key / value pair in the response properties of an Extended ECM REST API call.

Parameters:

Name Type Description Default
response dict

REST response from an OTCS REST Call

required
key str

property name (key)

required
value str

value to find in the item with the matching key

required
return_key str

determines which value to return based on the name of the dict key

required

Returns: str: value of the property with the key defined in "return_key" or None if the lookup fails

Source code in pyxecm/otcs.py
def lookup_result_value(
    self, response: dict, key: str, value: str, return_key: str
) -> str | None:
    """Lookup a property value based on a provided key / value pair in the
       response properties of an Extended ECM REST API call.

    Args:
        response (dict): REST response from an OTCS REST Call
        key (str): property name (key)
        value (str): value to find in the item with the matching key
        return_key (str): determines which value to return based on the name of the dict key
    Returns:
        str: value of the property with the key defined in "return_key"
             or None if the lookup fails
    """

    if not response:
        return None
    if not "results" in response:
        return None

    results = response["results"]
    # check if results is a list or a dict (both is possible -
    # dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value:
        data = results["data"]
        if isinstance(data, dict):
            # data is a dict - we don't need index value:
            properties = data["properties"]
            if (
                key in properties
                and properties[key] == value
                and return_key in properties
            ):
                return properties[return_key]
            else:
                return None
        elif isinstance(data, list):
            # data is a list - this has typically just one item, so we use 0 as index
            for item in data:
                properties = item["properties"]
                if (
                    key in properties
                    and properties[key] == value
                    and return_key in properties
                ):
                    return properties[return_key]
            return None
        else:
            logger.error(
                "Data needs to be a list or dict but it is -> %s", str(type(data))
            )
            return None
    elif isinstance(results, list):
        # result is a list - we need index value
        for result in results:
            data = result["data"]
            if isinstance(data, dict):
                # data is a dict - we don't need index value:
                properties = data["properties"]
                if (
                    key in properties
                    and properties[key] == value
                    and return_key in properties
                ):
                    return properties[return_key]
            elif isinstance(data, list):
                # data is a list we iterate through the list and try to find the key:
                for item in data:
                    properties = item["properties"]
                    if (
                        key in properties
                        and properties[key] == value
                        and return_key in properties
                    ):
                        return properties[return_key]
            else:
                logger.error(
                    "Data needs to be a list or dict but it is -> %s",
                    str(type(data)),
                )
                return None
        return None
    else:
        logger.error(
            "Result needs to be a list or dict but it is -> %s", str(type(results))
        )
        return None

parse_request_response(response_object, additional_error_message='', show_error=True)

Converts the text property of a request response object to a Python dict in a safe way that also handles exceptions.

Content Server may produce corrupt response when it gets restarted
or hitting resource limits. So we try to avoid a fatal error and bail
out more gracefully.

Parameters:

Name Type Description Default
response_object object

this is reponse object delivered by the request call

required
additional_error_message str

print a custom error message

''
show_error bool

if True log an error, if False log a warning

True

Returns:

Name Type Description
dict dict | None

response or None in case of an error

Source code in pyxecm/otcs.py
def parse_request_response(
    self,
    response_object: object,
    additional_error_message: str = "",
    show_error: bool = True,
) -> dict | None:
    """Converts the text property of a request response object to a Python dict in a safe way
        that also handles exceptions.

        Content Server may produce corrupt response when it gets restarted
        or hitting resource limits. So we try to avoid a fatal error and bail
        out more gracefully.

    Args:
        response_object (object): this is reponse object delivered by the request call
        additional_error_message (str): print a custom error message
        show_error (bool): if True log an error, if False log a warning

    Returns:
        dict: response or None in case of an error
    """

    if not response_object:
        return None

    try:
        dict_object = json.loads(response_object.text)
    except json.JSONDecodeError as exception:
        if additional_error_message:
            message = "Cannot decode response as JSon. {}; error -> {}".format(
                additional_error_message, exception
            )
        else:
            message = "Cannot decode response as JSon; error -> {}".format(
                exception
            )
        if show_error:
            logger.error(message)
        else:
            logger.warning(message)
        return None
    else:
        return dict_object

register_workspace_template(node_id)

Register a workspace template as project template for Extended ECM for Engineering Args: node_id (int): node ID of the Extended ECM workspace template Returns: dict: Response of request or None if the registration of the workspace template has failed.

Source code in pyxecm/otcs.py
def register_workspace_template(self, node_id: int) -> dict | None:
    """Register a workspace template as project template for Extended ECM for Engineering
    Args:
        node_id (int): node ID of the Extended ECM workspace template
    Returns:
        dict: Response of request or None if the registration of the workspace template has failed.
    """

    registration_post_data = {"ids": "{{ {} }}".format(node_id)}

    request_url = self.config()["xEngProjectTemplateUrl"]

    request_header = self.request_form_header()

    logger.info(
        "Register workspace template with ID -> %s; calling -> %s",
        str(node_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=registration_post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to register Workspace Template with ID -> %s; status -> %s; error -> %s",
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

remove_member_from_workspace(workspace_id, role_id, member_id, show_warning=True)

Remove a member from a workspace role. Check that the user is currently a member.

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
role_id int

ID of the role

required
member_id int

User or Group Id

required
show_warning bool

If True logs a warning if member is not in role

True

Returns: dict: Workspace Role Membership or None if the request fails.

Source code in pyxecm/otcs.py
def remove_member_from_workspace(
    self, workspace_id: int, role_id: int, member_id: int, show_warning: bool = True
) -> dict | None:
    """Remove a member from a workspace role. Check that the user is currently a member.

    Args:
        workspace_id (int): ID of the workspace
        role_id (int): ID of the role
        member_id (int): User or Group Id
        show_warning (bool, optional): If True logs a warning if member is not in role
    Returns:
        dict: Workspace Role Membership or None if the request fails.
    """

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/roles/{}/members".format(workspace_id, role_id)
    request_header = self.request_form_header()

    logger.info(
        "Check if user/group with ID -> %s is in role with ID -> %s of workspace with ID -> %s; calling -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
        request_url,
    )

    response = requests.get(
        url=request_url,
        headers=request_header,
        cookies=self.cookie(),
        timeout=None,
    )
    if not response.ok:
        logger.error(
            "Failed to get workspace members; status -> %s; error -> %s",
            response.status_code,
            response.text,
        )
        return None

    workspace_members = self.parse_request_response(response)

    if not self.exist_result_item(workspace_members, "id", member_id):
        if show_warning:
            logger.warning(
                "User/group with ID -> %s is not a member of role with ID -> %s of workspace with ID -> %s",
                str(member_id),
                str(role_id),
                str(workspace_id),
            )
        return None

    request_url = self.config()[
        "businessWorkspacesUrl"
    ] + "/{}/roles/{}/members/{}".format(workspace_id, role_id, member_id)

    logger.info(
        "Removing user/group with ID -> %s from role with ID -> %s of workspace with ID -> %s; calling -> %s",
        str(member_id),
        str(role_id),
        str(workspace_id),
        request_url,
    )

    response = requests.delete(
        url=request_url,
        headers=request_header,
        cookies=self.cookie(),
        timeout=None,
    )

    if response.ok:
        return self.parse_request_response(response)
    else:
        logger.error(
            "Failed to remove user/group with ID -> %s from role with ID -> %s of workspace with ID -> %s; status -> %s; error -> %s",
            str(member_id),
            str(role_id),
            str(workspace_id),
            response.status_code,
            response.text,
        )
        return None

rename_node(node_id, name, description, name_multilingual=None, description_multilingual=None)

Change the name and description of a node.

Parameters:

Name Type Description Default
node_id int

ID of the node. You can use the get_volume() function below to to the node id for a volume.

required
name str

New name of the node.

required
description str

New description of the node.

required
name_multilingual dict

multi-lingual node names

None
description_multilingual dict

multi-lingual description

None

Returns: dict: Request response or None if the renaming fails.

Source code in pyxecm/otcs.py
def rename_node(
    self,
    node_id: int,
    name: str,
    description: str,
    name_multilingual: dict | None = None,
    description_multilingual: dict | None = None,
) -> dict | None:
    """Change the name and description of a node.

    Args:
        node_id (int): ID of the node. You can use the get_volume() function below to
                           to the node id for a volume.
        name (str): New name of the node.
        description (str): New description of the node.
        name_multilingual (dict, optional): multi-lingual node names
        description_multilingual (dict, optional): multi-lingual description
    Returns:
        dict: Request response or None if the renaming fails.
    """

    rename_node_put_body = {"name": name, "description": description}

    if name_multilingual:
        rename_node_put_body["name_multilingual"] = name_multilingual
    if description_multilingual:
        rename_node_put_body["description_multilingual"] = description_multilingual

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.info(
        "Renaming node with ID -> %s to -> %s; calling -> %s",
        str(node_id),
        name,
        request_url,
    )

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            data={"body": json.dumps(rename_node_put_body)},
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to rename node with ID -> %s to -> %s; status -> %s; error -> %s",
                str(node_id),
                name,
                response.status_code,
                response.text,
            )
            return None

replace_transport_placeholders(zip_file_path, replacements)

Search and replace strings in the XML files of the transport package

Parameters:

Name Type Description Default
zip_file_path str

Path to transport zip file

required
replacements list of dicts

List of replacement values; dict needs to have two values: * placeholder: text to replace * value: text to replace with

required

Returns: Filename to the updated zip file

Source code in pyxecm/otcs.py
def replace_transport_placeholders(
    self, zip_file_path: str, replacements: list
) -> bool:
    """Search and replace strings in the XML files of the transport package

    Args:
        zip_file_path (str): Path to transport zip file
        replacements (list of dicts): List of replacement values; dict needs to have two values:
                                     * placeholder: text to replace
                                     * value: text to replace with
    Returns:
        Filename to the updated zip file
    """

    if not os.path.isfile(zip_file_path):
        logger.error("Zip file -> %s not found.", zip_file_path)
        return False

    # Extract the zip file to a temporary directory
    zip_file_folder = os.path.splitext(zip_file_path)[0]
    with zipfile.ZipFile(zip_file_path, "r") as zfile:
        zfile.extractall(zip_file_folder)

    modified = False

    # Replace search pattern with replace string in all XML files in the directory and its subdirectories
    for replacement in replacements:
        if not "value" in replacement:
            logger.error(
                "Replacement needs a value but it is not specified. Skipping..."
            )
            continue
        if "enabled" in replacement and not replacement["enabled"]:
            logger.info(
                "Replacement for transport -> %s is disabled. Skipping...",
                zip_file_path,
            )
            continue
        # there are two types of replacements:
        # 1. XPath - more elegant and powerful
        # 2. Search & Replace - basically treat the XML file like a text file and do a search & replace
        if "xpath" in replacement:
            logger.info(
                "Using xpath -> %s to narrow down the replacement",
                replacement["xpath"],
            )
            if "setting" in replacement:
                logger.info(
                    "Looking up setting -> %s in XML element",
                    replacement["setting"],
                )
            if "assoc_elem" in replacement:
                logger.info(
                    "Looking up assoc element -> %s in XML element",
                    replacement["assoc_elem"],
                )
        else:  # we have a simple "search & replace" replacement
            if not "placeholder" in replacement:
                logger.error(
                    "Replacement without an xpath needs a placeholder value but it is not specified. Skipping..."
                )
                continue
            if replacement.get("placeholder") == replacement["value"]:
                logger.info(
                    "Placeholder and replacement are identical -> %s. Skipping...",
                    replacement["value"],
                )
                continue
            logger.info(
                "Replace -> %s with -> %s in Transport package -> %s",
                replacement["placeholder"],
                replacement["value"],
                zip_file_folder,
            )

        found = XML.replace_in_xml_files(
            zip_file_folder,
            replacement.get("placeholder"),
            replacement["value"],
            replacement.get("xpath"),
            replacement.get("setting"),
            replacement.get("assoc_elem"),
        )
        if found:
            logger.info(
                "Replacement -> %s has been completed successfully for Transport package -> %s",
                replacement,
                zip_file_folder,
            )
            modified = True
        else:
            logger.warning(
                "Replacement -> %s not found in Transport package -> %s",
                replacement,
                zip_file_folder,
            )

    if not modified:
        logger.warning(
            "None of the specified replacements have been found in Transport package -> %s. No need to create a new transport package.",
            zip_file_folder,
        )
        return False

    # Create the new zip file and add all files from the directory to it
    new_zip_file_path = (
        os.path.dirname(zip_file_path) + "/new_" + os.path.basename(zip_file_path)
    )
    logger.info(
        "Content of transport -> %s has been modified - repacking to new zip file -> %s",
        zip_file_folder,
        new_zip_file_path,
    )
    with zipfile.ZipFile(new_zip_file_path, "w", zipfile.ZIP_DEFLATED) as zip_ref:
        for subdir, _, files in os.walk(
            zip_file_folder
        ):  # 2nd parameter is not used, thus using _ instead of dirs
            for file in files:
                file_path = os.path.join(subdir, file)
                rel_path = os.path.relpath(file_path, zip_file_folder)
                zip_ref.write(file_path, arcname=rel_path)

    # Close the new zip file and delete the temporary directory
    zip_ref.close()
    old_zip_file_path = (
        os.path.dirname(zip_file_path) + "/old_" + os.path.basename(zip_file_path)
    )
    logger.info(
        "Rename orginal transport zip file -> %s to -> %s",
        zip_file_path,
        old_zip_file_path,
    )
    os.rename(zip_file_path, old_zip_file_path)
    logger.info(
        "Rename new transport zip file -> %s to -> %s",
        new_zip_file_path,
        zip_file_path,
    )
    os.rename(new_zip_file_path, zip_file_path)

    # Return the path to the new zip file
    return True

request_download_header()

Deliver the request header used for the CRUD REST API calls. Consists of Cookie + Form Headers (see global vasriable)

Return: dict: request header values

Source code in pyxecm/otcs.py
def request_download_header(self) -> dict:
    """Deliver the request header used for the CRUD REST API calls.
       Consists of Cookie + Form Headers (see global vasriable)

    Args:
        None.
    Return:
        dict: request header values
    """

    # create union of two dicts: cookie and headers
    # (with Python 3.9 this would be easier with the "|" operator)
    request_header = {}
    request_header.update(self.cookie())
    request_header.update(REQUEST_DOWNLOAD_HEADERS)

    return request_header

request_form_header()

Deliver the request header used for the CRUD REST API calls. Consists of Cookie + Form Headers (see global variable)

Return: dict: request header values

Source code in pyxecm/otcs.py
def request_form_header(self) -> dict:
    """Deliver the request header used for the CRUD REST API calls.
       Consists of Cookie + Form Headers (see global variable)

    Args:
        None.
    Return:
        dict: request header values
    """

    # create union of two dicts: cookie and headers
    # (with Python 3.9 this would be easier with the "|" operator)
    request_header = {}
    request_header.update(self.cookie())
    request_header.update(REQUEST_FORM_HEADERS)

    return request_header

request_json_header()

Deliver the request header for REST calls that require content type application/json. Consists of Cookie + Json Headers (see global variable)

Return: dict: request header values

Source code in pyxecm/otcs.py
def request_json_header(self) -> dict:
    """Deliver the request header for REST calls that require content type application/json.
       Consists of Cookie + Json Headers (see global variable)

    Args:
        None.
    Return:
        dict: request header values
    """

    # create union of two dicts: cookie and headers
    # (with Python 3.9 this would be easier with the "|" operator)
    request_header = {}
    request_header.update(self.cookie())
    request_header.update(REQUEST_JSON_HEADERS)

    return request_header

rest_url()

Returns the REST URL of Extended ECM

Returns:

Name Type Description
str str

REST URL

Source code in pyxecm/otcs.py
def rest_url(self) -> str:
    """Returns the REST URL of Extended ECM

    Returns:
        str: REST URL
    """
    return self.config()["restUrl"]

run_web_report(nickname, web_report_parameters=None)

Run a Web Report that is identified by its nick name.

Parameters:

Name Type Description Default
nickname str

nickname of the Web Reports node.

required
web_report_parameters dict

Parameters of the Web Report (names + value pairs)

None

Returns: dict: Response of the run Web Report request or None if the Web Report execution has failed.

Source code in pyxecm/otcs.py
def run_web_report(
    self, nickname: str, web_report_parameters: dict | None = None
) -> dict | None:
    """Run a Web Report that is identified by its nick name.

    Args:
        nickname (str): nickname of the Web Reports node.
        web_report_parameters (dict): Parameters of the Web Report (names + value pairs)
    Returns:
        dict: Response of the run Web Report request or None if the Web Report execution has failed.
    """

    # Avoid linter warning W0102:
    if web_report_parameters is None:
        web_report_parameters = {}

    request_url = self.config()["webReportsUrl"] + "/" + nickname
    request_header = self.request_form_header()

    logger.info(
        "Running Web Report with nickname -> %s; calling -> %s",
        nickname,
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=web_report_parameters,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to run web report with nickname -> %s; status -> %s; error -> %s",
                nickname,
                response.status_code,
                response.text,
            )
            return None

search(search_term, look_for='complexQuery', modifier='', slice_id=0, query_id=0, template_id=0, limit=100, page=1)

Search for a search term.

Parameters:

Name Type Description Default
search_term str), e.g. "test or OTSubType

189"

required
look_for str

'allwords', 'anywords', 'exactphrase', and 'complexquery'. If not specified, it defaults to 'complexQuery'.

'complexQuery'
modifier str

'synonymsof', 'relatedto', 'soundslike', 'wordbeginswith', and 'wordendswith'. If not specified or specify any value other than the available options, it will be ignored.

''
slice_id int

ID of an existing search slice

0
query_id int

ID of an saved search query

0
template_id int

ID of an saved search template

0
limit int

maximum number of results (default = 100)

100
page int

number of result page (default = 1 = 1st page)

1

Returns: dict: search response or None if the search fails.

Source code in pyxecm/otcs.py
def search(
    self,
    search_term: str,
    look_for: str = "complexQuery",
    modifier: str = "",
    slice_id: int = 0,
    query_id: int = 0,
    template_id: int = 0,
    limit: int = 100,
    page: int = 1,
) -> dict | None:
    """Search for a search term.

    Args:
        search_term (str), e.g. "test or OTSubType: 189"
        look_for (str, optional): 'allwords', 'anywords', 'exactphrase', and 'complexquery'.
                                  If not specified, it defaults to 'complexQuery'.
        modifier (str, optional): 'synonymsof', 'relatedto', 'soundslike', 'wordbeginswith',
                                  and 'wordendswith'.
                                  If not specified or specify any value other than the available options,
                                  it will be ignored.
        slice_id (int, optional): ID of an existing search slice
        query_id (int, optional): ID of an saved search query
        template_id (int, optional): ID of an saved search template
        limit (int, optional): maximum number of results (default = 100)
        page (int, optional): number of result page (default = 1 = 1st page)
    Returns:
        dict: search response or None if the search fails.
    """

    search_post_body = {
        "where": search_term,
        "lookfor": look_for,
        "page": page,
        "limit": limit,
    }

    if modifier:
        search_post_body["modifier"] = modifier
    if slice_id > 0:
        search_post_body["slice_id"] = slice_id
    if query_id > 0:
        search_post_body["query_id"] = query_id
    if template_id > 0:
        search_post_body["template_id"] = template_id

    request_url = self.config()["searchUrl"]
    request_header = self.request_form_header()

    logger.info("Search for term -> %s; calling -> %s", search_term, request_url)

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=search_post_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to search for term -> %s; status -> %s; error -> %s",
                search_term,
                response.status_code,
                response.text,
            )
            return None

search_user(value, field='where_name')

Find a user based on search criteria.

Parameters:

Name Type Description Default
value str

field value

required
field str

user field to search with (where_name, where_first_name, where_last_name)

'where_name'

Returns: dict: User information or None if the user couldn't be found (e.g. because it doesn't exist).

Example response:
{
    'collection': {
        'paging': {...},
        'sorting': {...}
    },
    'links': {
        'data': {...}
    },
    'results': [
        {
            'data': {
                'properties': {
                    'birth_date': None,
                    'business_email': 'dfoxhoven@M365x61936377.onmicrosoft.com',
                    'business_fax': None,
                    'business_phone': None,
                    'cell_phone': None,
                    'deleted': False,
                    'display_language': None,
                    'first_name': 'Deke',
                    'gender': None,
                    'group_id': 8005,
                    'home_address_1': None,
                    'home_address_2': None,
                    'home_fax': None,
                    'home_phone': None,
                    'id': 8562,
                    'initials': 'DF',
                    'last_name': 'Foxhoven',
                    'middle_name': None,
                    'name': 'dfoxhoven',
                    'name_formatted': 'Deke Foxhoven',
                    ...
                }
            }
        }
    ]
}
Source code in pyxecm/otcs.py
def search_user(self, value: str, field: str = "where_name") -> dict | None:
    """Find a user based on search criteria.

    Args:
        value (str): field value
        field (str): user field to search with (where_name, where_first_name, where_last_name)
    Returns:
        dict: User information or None if the user couldn't be found (e.g. because it doesn't exist).

        Example response:
        {
            'collection': {
                'paging': {...},
                'sorting': {...}
            },
            'links': {
                'data': {...}
            },
            'results': [
                {
                    'data': {
                        'properties': {
                            'birth_date': None,
                            'business_email': 'dfoxhoven@M365x61936377.onmicrosoft.com',
                            'business_fax': None,
                            'business_phone': None,
                            'cell_phone': None,
                            'deleted': False,
                            'display_language': None,
                            'first_name': 'Deke',
                            'gender': None,
                            'group_id': 8005,
                            'home_address_1': None,
                            'home_address_2': None,
                            'home_fax': None,
                            'home_phone': None,
                            'id': 8562,
                            'initials': 'DF',
                            'last_name': 'Foxhoven',
                            'middle_name': None,
                            'name': 'dfoxhoven',
                            'name_formatted': 'Deke Foxhoven',
                            ...
                        }
                    }
                }
            ]
        }
    """

    request_url = self.config()["membersUrlv2"] + "?" + field + "=" + value
    request_header = self.request_form_header()

    logger.info(
        "Searching user by field -> %s, value -> %s; calling -> %s",
        field,
        value,
        request_url,
    )

    retries = 0
    while True:
        response = requests.get(
            url=request_url,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Cannot find user with -> %s = %s; status -> %s; error -> %s",
                field,
                value,
                response.status_code,
                response.text,
            )
            return None

set_category_value(node_id, value, category_id, attribute_id, set_id=0, set_row=1)

Set a value to a specific attribute in a category. Categories and have sets (groupings), multi-line sets (matrix), and multi-value attributes (list of values). This method supports all variants.

Parameters:

Name Type Description Default
node_id int

ID of the node

required
value multi - typed

value to be set - can be string or list of strings (for multi-value attributes)

required
category_id int

ID of the category object

required
attribute_id int

ID of the attribute

required
set_id int

ID of the set. Defaults to 0.

0
set_row int

Row of . Defaults to 1.

1

Returns:

Name Type Description
dict dict | None

REST API response or None if the call fails

Source code in pyxecm/otcs.py
def set_category_value(
    self,
    node_id: int,
    value,
    category_id: int,
    attribute_id: int,
    set_id: int = 0,
    set_row: int = 1,
) -> dict | None:
    """Set a value to a specific attribute in a category. Categories and have sets (groupings), multi-line sets (matrix),
       and multi-value attributes (list of values). This method supports all variants.

    Args:
        node_id (int): ID of the node
        value (multi-typed): value to be set - can be string or list of strings (for multi-value attributes)
        category_id (int):ID of the category object
        attribute_id (int): ID of the attribute
        set_id (int, optional): ID of the set. Defaults to 0.
        set_row (int, optional): Row of . Defaults to 1.

    Returns:
        dict: REST API response or None if the call fails
    """

    request_url = (
        self.config()["nodesUrlv2"]
        + "/"
        + str(node_id)
        + "/categories/"
        + str(category_id)
    )
    request_header = self.request_form_header()

    if set_id:
        logger.info(
            "Assign value -> %s to category with ID -> %s, set ID -> %s, row -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
            str(value),
            str(category_id),
            str(set_id),
            str(set_row),
            str(attribute_id),
            str(node_id),
            request_url,
        )
        category_put_data = {
            "category_id": category_id,
            "{}_{}_{}_{}".format(category_id, set_id, set_row, attribute_id): value,
        }
    else:
        logger.info(
            "Assign value -> %s to category ID -> %s, attribute ID -> %s on node with ID -> %s; calling -> %s",
            str(value),
            str(category_id),
            str(attribute_id),
            str(node_id),
            request_url,
        )
        category_put_data = {
            "category_id": category_id,
            "{}_{}".format(category_id, attribute_id): value,
        }

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            data=category_put_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to set value -> %s for category with ID -> %s, attribute ID -> %s on node ID -> %s; status -> %s; error -> %s",
                str(value),
                str(category_id),
                str(attribute_id),
                str(node_id),
                response.status_code,
                response.text,
            )
            return None

set_credentials(username='admin', password='')

Set the credentials for Extended ECM for the based on user name and password.

Parameters:

Name Type Description Default
username str

Username. Defaults to "admin".

'admin'
password str

Password of the user. Defaults to "".

''
Source code in pyxecm/otcs.py
def set_credentials(self, username: str = "admin", password: str = ""):
    """Set the credentials for Extended ECM for the based on user name and password.

    Args:
        username (str, optional): Username. Defaults to "admin".
        password (str, optional): Password of the user. Defaults to "".
    """
    self.config()["username"] = username
    self.config()["password"] = password

set_hostname(hostname)

Sets the hostname of Extended ECM

Parameters:

Name Type Description Default
hostname str

new hostname

required
Source code in pyxecm/otcs.py
def set_hostname(self, hostname: str):
    """Sets the hostname of Extended ECM

    Args:
        hostname (str): new hostname
    """
    self.config()["hostname"] = hostname

set_node_nickname(node_id, nickname, show_error=False)

Assign a nickname to an Extended ECM node (e.g. workspace)

Parameters:

Name Type Description Default
nickname str

Nickname of the node.

required
show_error bool

treat as error if node is not found

False

Returns: dict: Node information or None if no node with this nickname is found.

Source code in pyxecm/otcs.py
def set_node_nickname(
    self, node_id: int, nickname: str, show_error: bool = False
) -> dict | None:
    """Assign a nickname to an Extended ECM node (e.g. workspace)

    Args:
        nickname (str): Nickname of the node.
        show_error (bool): treat as error if node is not found
    Returns:
        dict: Node information or None if no node with this nickname is found.
    """

    nickname_put_body = {"nickname": nickname}

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id) + "/nicknames"
    request_header = self.request_form_header()

    logger.info(
        "Assign nickname -> %s to node with ID -> %s; calling -> %s",
        nickname,
        node_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            data=nickname_put_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            if show_error:
                logger.error(
                    "Failed to assign nickname -> %s to node ID -> %s; status -> %s; error -> %s",
                    nickname,
                    node_id,
                    response.status_code,
                    response.text,
                )
            else:
                logger.info(
                    "Cannot assign nickname -> %s to node ID -> %s. Maybe the nickname is already in use or the node does not exist.",
                    nickname,
                    node_id,
                )
            return None

unpack_transport_package(package_id, workbench_id)

Unpack an existing Transport Package into an existing Workbench.

Parameters:

Name Type Description Default
package_id int

ID of package to be unpacked

required
workbench_id int

ID of target workbench

required

Returns: dict: Unpack response or None if the unpacking fails.

Source code in pyxecm/otcs.py
def unpack_transport_package(
    self, package_id: int, workbench_id: int
) -> dict | None:
    """Unpack an existing Transport Package into an existing Workbench.

    Args:
        package_id (int): ID of package to be unpacked
        workbench_id (int): ID of target workbench
    Returns:
        dict: Unpack response or None if the unpacking fails.
    """

    unpack_package_post_data = {"workbench_id": workbench_id}

    request_url = self.config()["nodesUrlv2"] + "/" + str(package_id) + "/unpack"
    request_header = self.request_form_header()

    logger.info(
        "Unpack transport package with ID -> %s into workbench with ID -> %s; calling -> %s",
        str(package_id),
        str(workbench_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=unpack_package_post_data,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to unpack package -> %s; to workbench -> %s; status -> %s; error -> %s",
                str(package_id),
                str(workbench_id),
                response.status_code,
                response.text,
            )
            return None

update_item(node_id, parent_id=0, item_name='', item_description='')

Update an Extended ECM item (parent, name, description). Changing the parent ID is a move operation. If parent ID = 0 the item will not be moved.

Parameters:

Name Type Description Default
node_id int

ID of the node

required
parent_id int

node ID of the new parent (in case of a move operation)

0
item_name str

new name of the item

''
item_description str

new description of the item

''

Returns: dict: Response of the update item request or None if the REST call has failed.

Source code in pyxecm/otcs.py
def update_item(
    self,
    node_id: int,
    parent_id: int = 0,
    item_name: str = "",
    item_description: str = "",
) -> dict | None:
    """Update an Extended ECM item (parent, name, description). Changing the parent ID is
       a move operation. If parent ID = 0 the item will not be moved.

    Args:
        node_id (int): ID of the node
        parent_id (int, optional): node ID of the new parent (in case of a move operation)
        item_name (str, optional): new name of the item
        item_description (str, optional): new description of the item
    Returns:
        dict: Response of the update item request or None if the REST call has failed.
    """

    update_item_put_data = {}

    if item_name:
        # this is a rename operation
        update_item_put_data["name"] = item_name
    if item_description:
        # this is a change description operation
        update_item_put_data["description"] = item_description
    if parent_id:
        # this is a move operation
        update_item_put_data["parent_id"] = parent_id

    request_url = self.config()["nodesUrlv2"] + "/" + str(node_id)
    request_header = self.request_form_header()

    logger.info(
        "Update item -> %s with data -> %s; calling -> %s",
        item_name,
        str(update_item_put_data),
        request_url,
    )

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.put(
            url=request_url,
            data={"body": json.dumps(update_item_put_data)},
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update item -> %s; status -> %s; error -> %s",
                item_name,
                response.status_code,
                response.text,
            )
            return None

update_records_management_codes(rm_codes)

Update Records Management Codes. These are the most basic data types of the Records Management configuration and required to create RSIs and other higher-level Records Management configurations THIS METHOD IS CURRENTLY NOT WORKING

Parameters:

Name Type Description Default
rm_codes dict

Codes to be updated

required

Returns: dict: RSI data or None if the request fails.

Source code in pyxecm/otcs.py
def update_records_management_codes(self, rm_codes: dict) -> dict | None:
    """Update Records Management Codes. These are the most basic data types of
       the Records Management configuration and required to create RSIs and
       other higher-level Records Management configurations
       THIS METHOD IS CURRENTLY NOT WORKING

    Args:
        rm_codes (dict): Codes to be updated
    Returns:
        dict: RSI data or None if the request fails.
    """

    update_rm_codes_post_data = {}

    request_url = self.config()["recordsManagementUrl"] + "/rmcodes"
    request_header = self.request_form_header()

    logger.info(
        "Update Records Management codes -> %s; calling -> %s",
        str(rm_codes),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            headers=request_header,
            data=update_rm_codes_post_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            rm_codes_dict = self.parse_request_response(response)
            return rm_codes_dict["results"]["data"]
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update Records Management codes; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

update_user(user_id, field, value)

Update a defined field for a user.

Parameters:

Name Type Description Default
user_id int

ID of the user

required
value str

field value

required
field str

user field

required

Returns: dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).

Source code in pyxecm/otcs.py
def update_user(self, user_id: int, field: str, value: str) -> dict | None:
    """Update a defined field for a user.

    Args:
        user_id (int): ID of the user
        value (str): field value
        field (str): user field
    Returns:
        dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).
    """

    user_put_body = {field: value}

    request_url = self.config()["membersUrlv2"] + "/" + str(user_id)
    request_header = self.request_form_header()

    logger.info(
        "Updating user with ID -> %s, field -> %s, value -> %s; calling -> %s",
        str(user_id),
        field,
        value,
        request_url,
    )
    logger.debug("User Attributes -> %s", str(user_put_body))

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            data=user_put_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update user with ID -> %s; status -> %s; error -> %s",
                str(user_id),
                response.status_code,
                response.text,
            )
            return None

update_user_photo(user_id, photo_id)

Update a user with a profile photo (which must be an existing node).

Parameters:

Name Type Description Default
user_id int

ID of the user

required
photo_id int

Node ID of the photo

required

Returns: dict: Node information or None if photo node is not found.

Source code in pyxecm/otcs.py
def update_user_photo(self, user_id: int, photo_id: int) -> dict | None:
    """Update a user with a profile photo (which must be an existing node).

    Args:
        user_id (int): ID of the user
        photo_id (int): Node ID of the photo
    Returns:
        dict: Node information or None if photo node is not found.
    """

    update_user_put_body = {"photo_id": photo_id}

    request_url = self.config()["membersUrl"] + "/" + str(user_id)
    request_header = self.request_form_header()

    logger.info(
        "Update user ID -> %s with photo ID -> %s; calling -> %s",
        user_id,
        photo_id,
        request_url,
    )

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            data=update_user_put_body,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update user with ID -> %s; status -> %s; error -> %s",
                str(user_id),
                response.status_code,
                response.text,
            )
            return None

update_user_profile(field, value, config_section='SmartUI')

Update a defined field for a user profile. IMPORTANT: this method needs to be called by the authenticated user

Parameters:

Name Type Description Default
field str

user profile field

required
value str

new field value

required
config_section str

name of the config section. Possible config_section values: * SmartUI * General * Colors * ContentIntelligence * Discussion * Follow Up * Template Workspaces * Workflow * XECMGOVSettings * CommunitySettings * RecMan * PhysObj

'SmartUI'

Returns: dict: User information or None if the user couldn't be updated (e.g. because it doesn't exist).

Source code in pyxecm/otcs.py
def update_user_profile(
    self, field: str, value: str, config_section: str = "SmartUI"
) -> dict | None:
    """Update a defined field for a user profile.
       IMPORTANT: this method needs to be called by the authenticated user

    Args:
        field (str): user profile field
        value (str): new field value
        config_section (str, optional): name of the config section. Possible config_section values:
                                        * SmartUI
                                        * General
                                        * Colors
                                        * ContentIntelligence
                                        * Discussion
                                        * Follow Up
                                        * Template Workspaces
                                        * Workflow
                                        * XECMGOVSettings
                                        * CommunitySettings
                                        * RecMan
                                        * PhysObj
    Returns:
        dict: User information or None if the user couldn't be updated
              (e.g. because it doesn't exist).
    """

    user_profile_put_body = {config_section: {field: value}}

    request_url = self.config()["membersUrlv2"] + "/preferences"
    request_header = self.request_form_header()

    logger.info(
        "Updating profile for current user, field -> %s, value -> %s; calling -> %s",
        field,
        value,
        request_url,
    )
    logger.debug("User Attributes -> %s", str(user_profile_put_body))

    retries = 0
    while True:
        # This REST API needs a special treatment: we encapsulate the payload as JSON into a "body" tag.
        response = requests.put(
            url=request_url,
            data={"body": json.dumps(user_profile_put_body)},
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update profile of current user; status -> %s; error -> %s",
                response.status_code,
                response.text,
            )
            return None

update_workspace_aviator(workspace_id, status)

Enable or disable the Content Aviator for a workspace

Parameters:

Name Type Description Default
workspace_id int

node ID of the workspace

required
status bool

True = enable, False = disable Content Aviator for this workspace

required

Returns: dict: REST response or None if the REST call fails.

Source code in pyxecm/otcs.py
def update_workspace_aviator(
    self,
    workspace_id: int,
    status: bool,
) -> dict | None:
    """Enable or disable the Content Aviator for a workspace

    Args:
        workspace_id (int): node ID of the workspace
        status (bool): True = enable, False = disable Content Aviator for this workspace
    Returns:
        dict: REST response or None if the REST call fails.
    """

    aviator_status_put_data = {
        "enabled": status,
    }

    request_url = self.config()["aiUrl"] + "/{}".format(workspace_id)
    request_header = self.request_form_header()

    if status is True:
        logger.info(
            "Enable Content Aviator for workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )
    else:
        logger.info(
            "Disable Content Aviator for workspace with ID -> %s; calling -> %s",
            str(workspace_id),
            request_url,
        )

    retries = 0
    while True:
        response = requests.put(
            url=request_url,
            headers=request_header,
            data=aviator_status_put_data,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to change status for Content Aviator on workspace with ID -> %s; status -> %s; error -> %s",
                str(workspace_id),
                response.status_code,
                response.text,
            )
            return None

update_workspace_icon(workspace_id, file_path, file_mimetype='image/*')

Update a workspace with a with a new icon (which is uploaded).

Parameters:

Name Type Description Default
workspace_id int

ID of the workspace

required
file_path str

path + filename of icon file

required
file_mimetype str

mimetype of the image

'image/*'

Returns: dict: Node information or None if REST call fails.

Source code in pyxecm/otcs.py
def update_workspace_icon(
    self, workspace_id: int, file_path: str, file_mimetype: str = "image/*"
) -> dict | None:
    """Update a workspace with a with a new icon (which is uploaded).

    Args:
        workspace_id (int): ID of the workspace
        file_path (str): path + filename of icon file
        file_mimetype (str, optional): mimetype of the image
    Returns:
        dict: Node information or None if REST call fails.
    """

    if not os.path.exists(file_path):
        logger.error("Workspace icon file does not exist -> %s", file_path)
        return None

    update_workspace_icon_post_body = {
        "file_content_type": file_mimetype,
        "file_filename": os.path.basename(file_path),
    }

    upload_workspace_icon_post_files = [
        (
            "file",
            (
                f"{os.path.basename(file_path)}",
                open(file_path, "rb"),
                file_mimetype,
            ),
        )
    ]

    request_url = (
        self.config()["businessWorkspacesUrl"] + "/" + str(workspace_id) + "/icons"
    )

    request_header = self.cookie()

    logger.info(
        "Update icon for workspace ID -> %s with icon file -> %s; calling -> %s",
        str(workspace_id),
        file_path,
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=update_workspace_icon_post_body,
            files=upload_workspace_icon_post_files,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to update workspace ID -> %s with new icon -> %s; status -> %s; error -> %s",
                str(workspace_id),
                file_path,
                response.status_code,
                response.text,
            )
            return None

upload_file_to_parent(file_url, file_name, mime_type, parent_id)

Fetch a file from a URL or local filesystem and upload it to a Content Server parent (folder).

Parameters:

Name Type Description Default
file_url str

URL to download file or local file

required
file_name str

name of the file

required
mime_type str

mimeType of the file

required
parent_id int

parent (ID) of the file to upload

required

Returns: dict: Upload response or None if the upload fails.

Source code in pyxecm/otcs.py
def upload_file_to_parent(
    self, file_url: str, file_name: str, mime_type: str, parent_id: int
) -> dict | None:
    """Fetch a file from a URL or local filesystem and upload it to a Content Server parent (folder).

    Args:
        file_url (str): URL to download file or local file
        file_name (str): name of the file
        mime_type (str): mimeType of the file
        parent_id (int): parent (ID) of the file to upload
    Returns:
        dict: Upload response or None if the upload fails.
    """

    if file_url.startswith("http"):
        # Download file from remote location specified by the file_url parameter
        # this must be a public place without authentication:
        logger.info("Download file from URL -> %s", file_url)

        try:
            response = requests.get(url=file_url, timeout=1200)
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return None
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return None
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return None
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return None

        logger.info(
            "Successfully downloaded file -> %s; status code -> %s",
            file_url,
            response.status_code,
        )
        file_content = response.content

    elif os.path.exists(file_url):
        logger.info("Uploading local file -> %s", file_url)
        file_content = open(file=file_url, mode="rb")

    else:
        logger.warning("Cannot access -> %s", file_url)
        return None

    upload_post_data = {
        "type": str(144),
        "name": file_name,
        "parent_id": str(parent_id),
    }
    upload_post_files = [("file", (f"{file_name}", file_content, mime_type))]

    request_url = self.config()["nodesUrlv2"]
    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 500 response

    logger.info(
        "Uploading file -> %s with mime type -> %s to parent with ID -> %s; calling -> %s",
        file_name,
        mime_type,
        str(parent_id),
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=upload_post_data,
            files=upload_post_files,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to upload file -> %s to parent -> %s; status -> %s; error -> %s",
                file_url,
                str(parent_id),
                response.status_code,
                response.text,
            )
            return None

upload_file_to_volume(package_url, file_name, mime_type, volume_type)

Fetch a file from a URL or local filesystem and upload it to a Content Server volume.

Parameters:

Name Type Description Default
package_url str

URL to download file

required
file_name str

name of the file

required
mime_type str

mimeType of the file

required
volume_type int

type (ID) of the volume

required

Returns: dict: Upload response or None if the upload fails.

Source code in pyxecm/otcs.py
def upload_file_to_volume(
    self, package_url: str, file_name: str, mime_type: str, volume_type: int
) -> dict | None:
    """Fetch a file from a URL or local filesystem and upload it to a Content Server volume.

    Args:
        package_url (str): URL to download file
        file_name (str): name of the file
        mime_type (str): mimeType of the file
        volume_type (int): type (ID) of the volume
    Returns:
        dict: Upload response or None if the upload fails.
    """

    if package_url.startswith("http"):
        # Download file from remote location specified by the packageUrl
        # this must be a public place without authentication:
        logger.info("Download transport package from URL -> %s", package_url)

        try:
            package = requests.get(url=package_url, timeout=1200)
            package.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            logger.error("Http Error -> %s", errh.strerror)
            return None
        except requests.exceptions.ConnectionError as errc:
            logger.error("Error Connecting -> %s", errc.strerror)
            return None
        except requests.exceptions.Timeout as errt:
            logger.error("Timeout Error -> %s", errt.strerror)
            return None
        except requests.exceptions.RequestException as err:
            logger.error("Request error -> %s", err.strerror)
            return None

        logger.info(
            "Successfully downloaded package -> %s; status code -> %s",
            package_url,
            package.status_code,
        )
        file = package.content

    elif os.path.exists(package_url):
        logger.info("Using local package -> %s", package_url)
        file = open(file=package_url, mode="rb")

    else:
        logger.warning("Cannot access -> %s", package_url)
        return None

    upload_post_data = {"type": str(volume_type), "name": file_name}
    upload_post_files = [("file", (f"{file_name}", file, mime_type))]

    request_url = self.config()["nodesUrlv2"]
    request_header = (
        self.cookie()
    )  # for some reason we have to omit the other header parts here - otherwise we get a 500 response

    logger.info(
        "Uploading package -> %s with mime type -> %s; calling -> %s",
        file_name,
        mime_type,
        request_url,
    )

    retries = 0
    while True:
        response = requests.post(
            url=request_url,
            data=upload_post_data,
            files=upload_post_files,
            headers=request_header,
            cookies=self.cookie(),
            timeout=None,
        )
        if response.ok:
            return self.parse_request_response(response)
        # Check if Session has expired - then re-authenticate and try once more
        elif response.status_code == 401 and retries == 0:
            logger.warning("Session has expired - try to re-authenticate...")
            self.authenticate(revalidate=True)
            retries += 1
        else:
            logger.error(
                "Failed to upload file -> %s to volume of type -> %s; status -> %s; error -> %s",
                package_url,
                str(volume_type),
                response.status_code,
                response.text,
            )
            return None

volume_translator(current_node_id, translator, languages, simulate=False)

Experimental code to translate the item names and item descriptions in a given hierarchy. The actual translation is done by a tranlator object. This recursive method just traverses the hierarchy and calls the translate() method of the translator object.

Parameters:

Name Type Description Default
current_node_id int

current node ID to translate

required
translator object

this object needs to be created based on the "Translator" class and passed to this method

required
languages list

list of target languages

required
simulate bool

if True, do not really rename but just traverse and log info. the default is False

False
Source code in pyxecm/otcs.py
def volume_translator(
    self,
    current_node_id: int,
    translator: object,
    languages: list,
    simulate: bool = False,
):
    """Experimental code to translate the item names and item descriptions in a given hierarchy.
       The actual translation is done by a tranlator object. This recursive method just
       traverses the hierarchy and calls the translate() method of the translator object.

    Args:
        current_node_id (int): current node ID to translate
        translator (object): this object needs to be created based on the "Translator" class
                             and passed to this method
        languages (list): list of target languages
        simulate (bool, optional): if True, do not really rename but just traverse and log info.
                                   the default is False
    """
    # Get current node based on the ID:
    current_node = self.get_node(current_node_id)
    current_node_id = self.get_result_value(current_node, "id")

    name = self.get_result_value(current_node, "name")
    description = self.get_result_value(current_node, "description")
    names_multilingual = self.get_result_value(current_node, "name_multilingual")
    descriptions_multilingual = self.get_result_value(
        current_node, "description_multilingual"
    )

    for language in languages:
        if language == "en":
            continue
        # Does the language not exist as metadata language or is it already translated?
        # Then we skip this language:
        if (
            language in names_multilingual
            and names_multilingual["en"]
            and not names_multilingual[language]
        ):
            names_multilingual[language] = translator.translate(
                "en", language, names_multilingual["en"]
            )
            logger.info(
                "Translate name of node -> %s from -> %s (%s) to -> %s (%s)",
                current_node_id,
                name,
                "en",
                names_multilingual[language],
                language,
            )
        if (
            language in descriptions_multilingual
            and descriptions_multilingual["en"]
            and not descriptions_multilingual[language]
        ):
            descriptions_multilingual[language] = translator.translate(
                "en", language, descriptions_multilingual["en"]
            )
            logger.info(
                "Translate description of node -> %s from -> %s (%s) to -> %s (%s)",
                current_node_id,
                name,
                "en",
                names_multilingual[language],
                language,
            )

    # Rename node multi-lingual:
    if not simulate:
        self.rename_node(
            current_node_id,
            name,
            description,
            names_multilingual,
            descriptions_multilingual,
        )

    # Get children nodes of the current node:
    results = self.get_subnodes(current_node_id, limit=200)["results"]

    # Recursive call of all subnodes:
    for result in results:
        self.volume_translator(
            result["data"]["properties"]["id"], translator, languages
        )